class parent
{
public:
double spot;
double r;
double theValue;
void CalcTheValue(double spotIn, double rIn)
{
spot = spotIn;
r = rIn;
theValue = spot*r;
}
virtualdouble getSpot() {return spot;}
virtualdouble getR() {return r;}
};
class child : public parent
{
public:
double getSpot() {return spot+10;}
double getR() {return r+10;}
};
int main()
{
vector <parent*> a;
parent h();
child c();
a.push_back(&h);
a.push_back(&c);
for (unsigned i = 0; i < a.size(); i++)
{
parent * p = a.at(i);
p->CalcTheValue(5,3);
cout <<p->getSpot()<<"\n";
cout <<p->getR()<<"\n";
}
system("PAUSE");
}
i kept getting compilation errors like
error C2664: 'std::vector<_Ty>::push_back' : cannot convert parameter 1 from 'parent (__cdecl *)(void)' to 'parent *const &'
1> with
1> [
1> _Ty=parent *
1> ]
1> Reason: cannot convert from 'parent (__cdecl *)(void)' to 'parent *const '
1> There is no context in which this conversion is possible
Could anyone help with the above example? i couldnt figured out the correct syntax. any suggestions are appreciated.
You are constructing the objects incorrectly. What you had looked more like a function declaration. Don't use () when constructing objects on the stack. In this case you should not create the objects on the stack. When you insert pointers to objects within a vector you would want to use heap so that you can control when the objects pointed to are destroyed. In the context of that main function it might not be so bad but in general you don't want to insert pointers into a vector and then have the objects be deleted without updating the vector.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
int main()
{
vector <parent*> a;
parent* p = new parent;
child* c = new child;
a.push_back(p);
a.push_back(c);
for (unsigned i = 0; i < a.size(); i++)
{
parent * p = a.at(i);
p->CalcTheValue(5,3);
cout <<p->getSpot()<<"\n";
cout <<p->getR()<<"\n";
cout << endl;
}
delete p;
delete c;
system("PAUSE");
}