I need help with a specific programming problem in C++ (not sure if this is even possible in C++). I need to be able to access all public member functions in Base class, but do not want to allocate memory for the Base class data while allocating the Derived class object.
Lets say, I have:
class Base
{
public:
Base();
~Base();
int GetFoo() { return foo; }
// other public member functions of Base class
private:
int foo;
// other data
};
class Derived : public Base
{
public:
Derived(Base *BasePtr);
Derived(Base &BaseRef);
~Derived();
double GetXyz() { return xyz; }
// other public member functions of Derived class
private:
double xyz;
// other data
};
Now, lets say I already have a Base class allocated and initialized. I want to create a new Derived class object by referring to that existing Base object and allocate memory only for the data specific to the Derived class. Following the above example, I would have already allocated memory for "int foo" in the Base class object and only want to allocate memory for "double xyz" in the Derived class object.
Base *basePtr = new Base();
Derived *derivedPtr = new Derived(basePtr); // what is the content of this function?
What should be the memory allocation or the constructor for the Derived class look-like? I want to inherit all data and member functions of the Base class, but without doing a "combined" data allocation of Base and Derived. I have tried overloading operator new but no luck. Any help is appreciated.