I have:
class BASE{
public:
virtual void func1() = 0;
};
Then I have some derived classes, like:
class Derived1 : public BASE{
public:
void func1() {...implementation....}
};
class Derived2 : public BASE{
public:
void func1() {...implementation....}
};
In the main I would like to do something like (pseudo code):
if ( cond ){
BASE b := new Derived1
}
else{
BASE b := new Derived2
}
b.func1();
so that the func1() function invoked is the one specialized for the derived class.
I tried to do:
BASE b = new Derived1();
but the compiler complains.
Is it possible to do that in C++? How?
There are two ways to do this:
Use a pointer of type base class:
Base *b = new Derived1;Use a const reference of type base class if you want to create a derived on copy construction:
Base const& b = Derived;Use a non-const reference of type base class if you want to assign a derived class object created elsewhere:
Derived d;Base& b = d;Nits:
In order to inherit, you need to specify this in the class definition:
class Derived1 : public Base {Your functions need to have a return value.
class B{public:
virtual void func() = 0;
};