I am trying to write a class which holds either a pointer to an object of class A(base) or class B(derived) depending on conditions at run time.
The base class and derived class:
class A
{
protected:
int x;
};
class B : public A
{
public:
int y, z;
};
And a third class which holds a pointer to the base class
class C
{
public:
C(bool derivedClass)
{
if (derivedClass)
{
pAB = new B;
}
else
{
pAB = new A;
}
}
A* pAB;
// other members
};
However, it seems that pAB is always pointing to class A(base) no matter what argument is sent to the constructor. How can I get this type of polymorphism, where I am only allocating memory for the correct class at run time?