help for a oop newb please

can someone help this is i need it to call individual update but it keeps calling base class update. here is the code
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
40
41
42
43
44
45
46
 #include <iostream>
#include <vector>
using namespace std;

class Shape
{
public:

Shape(){}
    
virtual void update(){cout << "Shape: Update\n";}
};


class SphereShape:public Shape
{
public:
float radius;

SphereShape():Shape(){radius = 10;}


virtual void update(){
     cout << "sphere update radius is: " << radius << endl;
    }
};



vector<Shape> shapes;



int main() {
	Shape testshape;
	shapes.push_back(testshape);
	SphereShape testsphere;
	shapes.push_back(testsphere);
	
	for(int i = 0;i < shapes.size();i++)
	  {
	  shapes[i].update();	
	  }
	
	return 0;
}


the output is
Shape: Update
Shape: Update

when in looking to have output
Shape: Update
sphere update radius is: 10

edit: changed to right code
Last edited on
Two problems:

line 11: must be virtual

For polymorphism to work, you need to use pointers.
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
#include <iostream>
#include <vector>
using namespace std;

class Shape
{
public:
    Shape(){}
    virtual void update()
    {   cout << "Shape: Update\n";  }
};

class SphereShape:public Shape
{
public:
    float radius;

    SphereShape()
    {   radius = 10;    }

    void update()
    {   cout << "sphere update radius is: " << radius << endl;  }
};

vector<Shape *> shapes;

int main() 
{   Shape testshape;
	shapes.push_back(&testshape);
	SphereShape testsphere;
	shapes.push_back(&testsphere);
	
	for (size_t i=0; i < shapes.size(); i++)
	{   shapes[i]->update();	
	}
	system ("pause");
	return 0;
}
Shape: Update
sphere update radius is: 10
Press any key to continue . . .


yup that works thank you is there a way to do it without pointers?
Not really. When you do not use pointers, you "slice" the sphere object data out and leave only the shape data when you put it in the container.
Topic archived. No new replies allowed.