Reputation: 18178
I have a code similar to this (simplified to help present the problem)
class a
{
protected:
int m_x;
public:
a(int x):m_x(x){};
~a(){};
virtual int GetX()=0;
}
class b:public a
{
public:
b(int x):a:(x){};
~b(){};
virtual int GetX(){return m_x+2;};
}
class c:public a
{
public:
c(int x):a:(x){};
~c(){};
virtual int GetX(){return m_x+4;};
}
I also have these functions:
vector<a> GetData()
{
vector<a> data;
data.push_back(b(1));
data.push_back(c(1));
}
void printData()
{
vector<a> data=GetData();
for(int I=0;i<data.size();I++)
{
cout<< data[I].GetX()<<endl;
}
}
The above program did not compile by error that a class with virtual function can not be instantiated.
so I changed a to this one:
class a
{
protected:
int m_x;
public:
a(int x):m_x(x){};
~a(){};
virtual int GetX()={return m_x};
}
But I am not getting the correct result as I thought since I created objects of type b and c then when I call GetX, their function should be called and not of a. so I am getting this data:
1
1
instead of
3
5
How can I fix this problem?
Is there any switch in compiler that I should turn on to get this to work?
I am using visual studio 2012.
Upvotes: 0
Views: 91
Reputation: 4387
You need to use a vector of pointers. Fortunately, since you are using VS2012, you have modern smart pointers (with some other C++11 goodness):
typedef std::vector<std::unique_ptr<a>> DataVector;
DataVector GetData() {
DataVector data;
data.push_back(std::unique_ptr<b>(new b(1)));
data.push_back(std::unique_ptr<c>(new c(1)));
return data;
}
void PrintData() {
for(const auto & datum : GetData())
std::cout << datum->GetX() << std::endl;
}
Upvotes: 1