Question:I have 3 classes that derive from each other:
main, I create an instance pointer of
ThreeDimentionaland set its value with a
Sphere. And then change its
rto 2. I think it somehow changes
rof the base class? because it returns the volume as 0. Isn’t sphere supposed to override the
rof base class? how can I change r of sphere?
Answer:You can’t override data members. You can override only virtual member functions.
Shapeis supposed to have a radius, then
Sphereshouldn’t declare another
r(which will just hide the one in
Shapedepending on the context from where it is named).
If only a
Sphereis supposed to have a radius, then it shouldn’t be possible to set
ThreeDimentionalpointer, which ought to be agnostic about what kind of
ThreeDimentionalobject the pointer is pointing to. (In circumstances where a decision must still be taken based on the derived type nonetheless,
dynamic_castcan be used.)
Which of the two applies depends on your intended interpretation for “radius”/
r, but typically only spheres have a radius in the strict sense.
If you have better answer, please add a comment about this, thank you!