1
class Road {
private:
    std::vector<Vehicle*> container;
public:
    std::vector<Vehicle*> getContainer(){
        return container;
    }
    virtual void operator+(Vehicle *vehicle)=0;
};


class Highway: public Road {
public:
    virtual void operator+(Vehicle *vehicle) {
         getContainer().push_back(vehicle);
     }
};

Why do I get an error that I cannot allocate an object of abstract type when all of my virtual functions are overriden? It happens when I try to call Road r = Highway(); in my main class.

yuri kilochek
  • 12,709
  • 2
  • 32
  • 59
Derik Daro
  • 97
  • 2
  • 9

1 Answers1

3

For Road r = Highway();, Road r means you're trying to define an object of type Road, which is an abstract class then the definition is not allowed. The initializer list part (i.e. = Highway()) doesn't affect the type of r, it just means r is slicing-copy initialized from an temporary object of type Highway.

You should use pointers/smart pointers or references with abstract class type, e.g.

Road* r = new Highway;
// using r ...
delete r;

or

Highway h;
Road& r = h;
// using r ...
Community
  • 1
  • 1
songyuanyao
  • 169,198
  • 16
  • 310
  • 405