If I have three classes - Base
, Derived1
and Derived2
, and I want to create a vector<Base*> collection
. When I try to copy the vector like this in another class' copy constructor:
for (Base *object: other.collection) {
this->collection.push_back(new Base(&object));
}
I get the error: Allocating an object of abstract class type 'Base'
. But even though the Base
class is abstract, I have defined the pure virtual methods in all derived classes, so there shouldn't be a problem:
class Base {
public:
Base();
virtual ~Base() = default;
virtual std::ostream &print(std::ostream &out) const = 0;
virtual std::istream &read(std::istream &in) = 0;
protected:
//something
};
class Derived1 : virtual public Base {
public:
Derived1();
virtual std::istream &read(std::istream &in); // has definition in .cpp file
virtual std::ostream &print(std::ostream &out) const; //also has definition in .cpp file
protected:
// something
};
class Derived2 : virtual public Base {
public:
Derived2();
virtual std::istream &read(std::istream &in); // has definition in .cpp file
virtual std::ostream &print(std::ostream &out) const; //also has definition in .cpp file
protected:
// something
};
Derived1
and Derived2
are jointly inherited by a fourth class, which, like these two, has the methods read()
and print()
defined. Why am I getting the error, even though all derived classes have the pure virtual methods implemented?