Is there a possibility (or a quick traversal) to create an object defined as a derived class without creating an object of the base class in memory; instead, should the derived object refer to the actually existing object of the base class ("take over" its memory)? This is necessary for speed reasons - creating a new derived object, copying data from the base class object to it, and then destroying the base object takes too much time.
In this case, you can consider composition instead of inheritance - this would be more natural.
class, . - , , struct v-table . , , , Linux. , - , .
class
struct
v-table
v-table , , realloc, , .
realloc
class, . .
EDIT: , , realloc - . , . copy , . , , , , , , boost.
copy
, , , , .
:
d1 = prestochango(b); d2 = prestochango(b); d1.blarf = waldo; // what value does d2.blarf now have?
d1 d2 , b-, .
, b- d.
, , v- .
, , " " , .
, .
, . Static .
.
class FooBase { protected: static int IDCnt; static int ObjCnt; int ID; public: FooBase(); ~FooBase(); virtual int GetID(); virtual int GetObjCnt(); virtual int GetIDCnt(); }; //implementation int FooBase::IDCnt = 0; //need to init static vars int FooBase::ObjCnt = 0; FooBase::FooBase() { ID = IDCnt; IDCnt++; ObjCnt++; } FooBase::~FooBase() { ObjCnt--; } int FooBase::GetID() { return ID; } int FooBase::GetObjCnt() { return ObjCnt; } int FooBase::GetIDCnt() { return IDCnt; } #include "FooBase.h" class FooDerived : public FooBase { //blah }; #include "FooDervied.h" int main() { FooDerived A; FooDerived B; cout << A.GetID() << ' ' << A.GetObjCnt() << ' ' << A.GetIDCnt() << endl; cout << B.GetID() << ' ' << B.GetObjCnt() << ' ' << B.GetIDCnt() << endl; if(true) { FooDerived C; cout << A.GetObjCnt() << ' ' << A.GetIDCnt() << ' ' << B.GetObjCnt << C.GetIDCnt() << endl; } cout << B.GetObjCnt() << '' << A.GetObjCnt() << ' ' << A.GetIDCnt() << ' ' << B.GetIDCnt << endl; }
, , , , FooDerived FooBase::IDCnt FooBase::ObjCnt.
FooDerived
FooBase::IDCnt
FooBase::ObjCnt
Have you considered the Factory design template?
Your base class only needs to know what kind of derived class you want to create.