Andreas Wollschlaeger wrote:
Lars Tetzlaff schrieb:
Andreas Wollschlaeger schrieb:
Hi folks,
as the subject says, i'm a poor Java programmer trying to transfer some
of his wisdom into C++ world... here is what im trying to do this
evening:
Java has a nifty feature called a static class initializer - something
like this:
You do not need to allocate every object with new in C++, so if you only
need a vector of Thing, use xx. If you need to allocate Thing on the
heap, use yy;
xx.h:
#include <vector>
class Thing
{
};
class Foo
{
private:
static std::vector<Thing> xx;
static class MyVector : public std::vector<Thing*>{ public:
MyVector(); } yy;
};
xx.cpp:
#include <xx.h>
std::vector<Thing> Foo::xx( 42 );
Foo::MyVector::MyVector()
{
for( int i = 0; i<42; ++i ) {
yy.push_back( new Thing() );
}
}
Foo::MyVector Foo::yy;
Well, great, this was just what i have been looking for: encapsulating
the statics initialization in some inner class and its default
constructor - much more elegant and "cplusplusish" than my previous
attempt :-) Tx to you and the other folks, added me some more insight
to C++ this evening!
I can see why that solution would look nice to a Java developer, but in
general, it's a bad idea to derive your own classes from the standard
ones; it is especially non-c++ish.
C++ methods aren't virtual by default; they're more like final methods
in Java. In particular, their destructors aren't virtual, so if ever an
instance of a derived type is deleted through a pointer to a base with a
non-virtual destructor, nasty things will happen. You're much better
off in this case with Victor or Juha's solutions, both of which are fine.
is known to the compiler and the right destructor is called. The class
was ment *only* to initialize the static member. Generally I would agree