Reputation: 1497
My last question was a mess. I'm getting the wrong output.
So here I have in my main:
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 shineExp = 3.0;
Sphere *s = new Sphere(Point(0.0,0.0,-5), 100.0, amb, difCoef, spec, shineExp);
shapes.push_back(s);
Where shapes is vector < Shape * > shapes;
Shape *x = shapes[0];
cout << "Shine" << x->shine << endl;
Prints out zero even though the answer should be 3.0.
The following are my classes:
#include "shape.h"
class Sphere : public Shape
{
public:
Point centerPt;
double radius;
Color ambient;
Color dif;
Color spec;
double shine;
Sphere(Point center, double rad, Color amb, Color difCoef, Color specu, double shineVal)
{
centerPt = center;
radius = rad;
ambient = amb;
dif = difCoef;
spec = specu;
shine = shineVal;
}
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;
};
Upvotes: 0
Views: 181
Reputation: 53289
The problem is that you're repeating your variable declarations in the derived class. You don't need to redeclare variables like double shine
, which are already in Shape
, in the derived class Sphere
. Since Sphere
inherits from Shape
, all the public member variables in Shape
are automatically inherited in Sphere
, and do not need to be redeclared. Redeclaring them will result in two different member variables, i.e. Sphere::shine
is a totally different variable from Shape::shine
.
Therefore, when you assign a value to Sphere::shine
, and then later access an instance of Sphere
with a base-class Shape
pointer, the value of shine
is not going to be what you expect.
Upvotes: 6
Reputation: 791631
Each instance of Sphere
has two variables called shine
. One is in the derived class and one is in the base class.
The Sphere
constructor initializers the derived Sphere::shine
, but x->shine
accesses the base class variable, because x
has type "pointer to Shape
". Member variables don't have any 'virtual' behaviour.
I'm almost certain that what you want is to keep the common variables in the base class Shape
and not redeclare identically named and type member variables in the derived class. You should only declare properties that are unique to the derived class in the derived class (such as centerPt
and radius
for Sphere
).
Upvotes: 1