tags:

views:

203

answers:

3
vector < Shape* > shapes;

void createScene()
{

 image = QImage(width, height, 32); // 32 Bit
 Color amb(0.1,0.1,0.1);
 Color difCoef(0.75,0.6,0.22);
 Color spec(0.5,0.5,0.5);
 double shine= 3.0;
 Sphere *s = new Sphere(Point(0.0,0.0,-5), 100.0, amb, difCoef, spec, shine);
 shapes.push_back(s);

}




int main(){

 // initialize glut
 init(); 
 createScene();
 Shape *x = shapes[0];
 cout << x->shine << endl;
}





class Shape
{
 public: 
 Shape() {}
 ~Shape(){} 
 Color ambient;
 Color dif;
 Color spec;
 double shine;
 virtual bool checkIntersect(Point p, Point d, Point &temp) = 0; // If intersects, return true else false.
 virtual Point getNormal(Point intPt) = 0; // Get the normal at the point of intersection
 //virtual void printstuff() = 0;

};

When it prints out shine, i get a value of zero? Why is that?

+2  A: 

I think object slicing occures (since you'r using a Shape object and assigning to it). What you would want to do in order to preserve polymorphism is use a pointer or a reference. In this case I would use a pointer:

Shape *x = shapes[0];

If shapes is an odd container which does de-reference (this is what i understand from your code) then I would use a reference:

Shape &x = shapes[0];

You could use a const reference, but it isnt mandatory here since your object is not a temporary one by any means.

Btw, hasn't anybody told you globals are a bad practice?

rmn
A: 

Assuming Shape is an base class of Sphere and others, you should not make a copy of it. Currently, you are (probably) slicing the object which is actually a Sphere by making a copy of its Shape base part.

Taking a pointer or a reference to the Shape object, as others have suggested, should solve your problem.

Josef Grahn
+2  A: 

This code cannot be compiling. If you have defined a container for Shape* as is implied by the lines

Sphere *s = new Sphere(Point(0.0,0.0,-5), 100.0, amb, difCoef, spec, shine);
shapes.push_back(s);

Then, you could not be retrieving a Shape from shapes as in

Shape x = shapes[0];
Dave
Unless he's using public inheritance and is accidentally slicing his Sphere instance into a Shape instance.
Joe Gauterin
@Joe: What does "public ineritance" have do do with it? In the first case it is a container of pointers, in the second - of objects themselves. The OP's code does not make any sense, as Dave correctly noted.
AndreyT
+1: The OP's code shouldn't even compile to begin with
Charles Salvia
It could be some custom container doing de-reference under the hood. I wouldn't be that surprised if the supplied code didn't compile, though. My answers covers both situations.
rmn