Creating a derived class object with an existing base class object?

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.

+3
source share
6 answers

In this case, you can consider composition instead of inheritance - this would be more natural.

+2
source

class, . - , , struct v-table . , , , Linux. , - , .

v-table , , realloc, , .

class, . .

EDIT: , , realloc - . , . copy , . , , , , , , boost.

+1

, , , , .

:

   d1 = prestochango(b);
   d2 = prestochango(b);
   d1.blarf = waldo;
   // what value does d2.blarf now have?

d1 d2 , b-, .

, b- d.

0

, , v- .

, , " " , .

, .

0

, . 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.

0
source

Have you considered the Factory design template?

Your base class only needs to know what kind of derived class you want to create.

0
source

All Articles