As the title states, I have a base class (interface) and several derived classes. On the derived classes, I have some extra functions that don't make sense to implement on the interface class - neither on all derived classes.
In my program, I have a vector of pointers to base classes - but the actual objects are all of derived classes.
Now, if I try to call a function of a derived class, I get a compiler error. Even if I know for sure the derived type that a particular object will have, I cannot call the function.
How do I get around this? Would this point to a design problem? Should I convert the pointer/create a new pointer of that specific type?
The last option seems to work, but makes the code very ugly with tons of if-else
blocks.
Here is some example code to reproduce the error:
#include <iostream>
class Base {
public:
Base() {};
~Base() = default;
};
class Derived: public Base {
public:
Derived() {};
~Derived() = default;
void foo() {
std::cout << "foo()" << std::endl;
}
};
int main()
{
Base* ptr = new Derived();
*ptr->foo();
delete ptr;
}
EDIT: I do know about virtual functions, but this is not what I'm looking for. My point is that it would make no sense to implement foo() on the base class nor on all of the derived classes. foo() is something very specific to one specific derived class. Example: my base class is Vehicle, my derived classes are Car, Helicopter, Speedboat. My function is checkTirepressure() - as you see this function doesn't make any sense on Helicopter or Speedboat.