I'm having trouble with constructors in derived classes. Lets say I have the simple code below here with one base class Base and two classes whom inherits from Base, Derived1 and Derived2.
I want Derived2 to hold a pointer to Base, which could point either to Base or Derived1. I cannot manage to write the constructor for this tho. If I pass in a Derived1 object I get a empty Base once inside the constructor.
Class Base
{
public:
Base(int a): m_a(a)
{
}
protected:
int m_a;
};
//First derived class of base
class Derived1 : public Base
{
public:
Derived1(double c): m_c(c)
{
}
private:
double m_c;
};
//Second derived class of Base
class Derived2 : public Base
{
public:
Derived2(Base b, int k): m_b(&b), m_k(k)
{
}
private:
int m_k;
Base* m_b;
};
int main()
{
Base b(2);
Derived1 d1(3.0);
Derived2 d2(d1, 3);
Derived2 d3(b, 4);
}
Derived2
instance will end up with a completely illegitimatem_b
value after construction. You're saving the address of a local variable (the copyBase b
, which you likely did not intend to be sliced, but none-the-less is.) – WhozCraigvirtual ~Base() {}
to the base class and use RTTI (dynamic_cast) as needed. Maybe you get rid of all derived member data and have a union in base (with an additional member describing the type (int, double, ...)) – user2249683