0

I have looked at other similar threads and this problem is different in the sense that I use std::vector. I have the following codes making use of inheritance in C++.

#include<iostream>
#include<vector>
using namespace std;

class Vehicle {
public:
    virtual void brake()=0;
};

class Car : public Vehicle {
public:
    virtual void brake() override;
};

void Car::brake() {
    cout<<"Brake applied"<<endl;
}

When I call brake() in this way it works:

int main() {
    Car c;
    c.brake(); // Brake applied
    return 0;
} 

However, when I call brake() using the following way, I get the error error: allocating an object of abstract class type 'Vehicle'

int main() {
    vector<Vehicle> vehicleList;
    vehicleList.push_back(c);
    vehicleList.at(0).brake(); 
    return 0;
}

Any help on not getting the error?

Mika
  • 1,195
  • 6
  • 22
  • 34
  • You possibly want `vector>` – M.M May 17 '18 at 21:05
  • The "duplicate" explains the problem but doesn't really offer any solution for this use case – M.M May 17 '18 at 21:05
  • @M.M Thanks. I found some solutions here: https://stackoverflow.com/questions/2973301/what-is-a-possible-workaround-for-object-slicing-in-c – Mika May 18 '18 at 05:52

0 Answers0