C++ Call derived function from base class instance

Dan picture Dan · Apr 2, 2012 · Viewed 7.6k times · Source

I am fairly new to C++, but i have ran into an issue which i cannot seem to resolve. I will use cars to illustrate the problem, just to make things easier. Okay so lets say that i have a base class Car, and i have different brands that are inheriting from that class. Like so:

class Car
{
    public:
       Car();
};

class Ford: public Car
{
    public:
        Ford();
        void drive();
        void park();
};

The whole idea is to put all these different cars together in single a vector of the type Car. Like so:

vector<Car*> cars;
cars.push_back(new Ford());
cars.back()->drive(); //this won't work

How can i call the derived function on the base class instance? Note that i want to place these all in a single vector. The reason behind this is because i only want to use the last derived car class instance that has been added.(In this case the derived car class is ford). Also note that all car classes will have the same functions.

Answer

Oliver Charlesworth picture Oliver Charlesworth · Apr 2, 2012

If these functions are truly common to all the derived classes, then you have a common interface, so you should express this via the base class. To do so, you declare these functions as pure-virtual:

class Car {
public:
    virtual void drive() = 0;  // Pure-virtual function
};

class Ford : public Car {
public:
    virtual void drive() { std::cout << "driving Ford\n"; }
};

...

vector<Car*> cars;
cars.push_back(new Ford());
cars.back()->drive(); //this will work

[On a side note, it's generally considered poor practice to have a vector of raw pointers, because it makes memory management tricky. You should consider using smart pointers.]