vector of inheritance class

hi,

im really new to C++ coming from a java/c# background and got stuck with some basic problem...

i try to create a vector of objects inheritted from the same super class as the following:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
class parent
{
	public:	
		double spot;
		double r;
		double theValue;
		void CalcTheValue(double spotIn, double rIn)
		{
			spot = spotIn;
			r = rIn;
			theValue = spot*r;
		} 
		virtual double getSpot() {return spot;}
		virtual double 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.

thanks
Last edited on
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");
}   
Last edited on
Topic archived. No new replies allowed.