Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different initialization of base class attribute

Consider a base class that has an attribute

class Base 
{
  protected:

  AttributeBase * elementPtr;
  ...
};

And a derived class

class Derived : public Base
{
  ...
};

Also I have a class AttributeDerived which derives from AttributeBase

When I create an object of the class Base I would like elementPtr to be initialized in this way:

elementPtr = new AttributeBase()

But when I create an object of the class Derived I would like elementPtr to be initialized in this way:

elementPtr = new AttributeDerived()

What is the cleanest way to do that?

like image 462
Issam T. Avatar asked Aug 13 '15 08:08

Issam T.


1 Answers

You could add a protected constructor to Base which allows the derived class to pass an elementPtr to use:

Base (AttributeBase* elementPtr) : elementPtr(elementPtr)
{}

Then in your derived class, call that constructor:

Derived() : Base(new AttributeDerived())
{}

If you use C++11, you could then have other Base constructors delegate to the protected one to limit code duplication.

like image 185
TartanLlama Avatar answered Sep 25 '22 14:09

TartanLlama