mercredi 2 janvier 2019

Is it possible to dynamically allocate the extra memory required for a derived class from an existing base class?

Is it possible to have a derived class add the extra memory to a pointer that is returned from somewhere else?

The reasoning is I am using a library that returns Base * to me, and I add some extra functionality to it with Derived *. The problem is I have to create a whole new object when doing this currently and am losing the original pointer which is used internally by the library for updates.

Example of what I am trying to do in simple code:

class Base 
{
public:
  Base() {}
  ~Base() = default;

  void BaseMethod();
private:
  int foo;
};

class Derived : public Base
{
public:
  Derived() : Base() {}
  ~Derived() = default;

  void DerivedMethod();
private:
  int bar;
}

// Somewhere else
Base* baseClass = new Base();

// This is the important part/question. 
// Is there some way to "allocate" the missing memory to make "baseClass" a Derived?
// I don't want to allocate an entirely new object, I just want to find out if it 
// is possible to allocate the missing memory to make Base a Derived 
// (and use the same pointer still)
Derived* derivedClass = SomehowAddExtraMemoryTo(baseClass);

Aucun commentaire:

Enregistrer un commentaire