0

I have an abstract class:

class myabsclass {
public:
    virtual int func1() = 0;
    virtual int func2() = 0;
};

And classes that implement it:

class myclass : public myabsclass {
public:
    myclass() {}
    int func1() { return 0; }
    int func2() { return 1; }
private:
    int a,b,c;
}

class myclass2 : public myabsclass {
public:
    myclass2() {}
    int func1() { return 3; }
    int func2() { return 4; }
private:
    int d,e,f;
}

If I have a vector that holds various types of implementions of the myabsclass abstract class:

vector<myabsclass> vec;

I get an error when I try to do this:

vec.push_back(myclass);
vec.push_back(myclass2);

Error message in VS2013 is:

Cannot instantiate abstract class

I'm trying to understand why, considering that I believe this should be valid. The vector needs to hold all different types of implementations of this class, so I can't afford to explicitly make it a vector of the implementors:

vector<myclass> vec; // Wont work since I need to put myclass2 in there.

Any ideas on why the compiler is choking? Is this a compiler bug?

2 Answers2

1

The vector itself stores copies of your instances, so it tries to copy elements of type myabsclass. This type of behaviour is only supported by pointers or references.

One solution is to use a std::shared_ptr.

std::vector<std::shared_ptr<myabsclass>> vec;
vec.push_back(std::make_shared<myclass2>());

Your question is very similar to Why can't we declare a std::vector<AbstractClass>?

Community
  • 1
  • 1
Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67
0

An abstract class cannot be instantiated so, making a vector of OBJECTS will try to copy them, and this is not possible.

A simple solution would be using a vector of pointers, doing this will allow you to use polymorphism.

std::vector<myabsclass*>
Drewen
  • 2,806
  • 1
  • 15
  • 12