Question:
I have 3 classes that derive from each other:main
, I create an instance pointer of ThreeDimentional
and set its value with a Sphere
.
And then change its r
to 2. I think it somehow changes r
of the base class? because it returns the volume as 0. Isn’t sphere supposed to override the r
of base class? how can I change r of sphere?Answer:
You can’t override data members. You can override only virtual member functions.If every
Shape
is supposed to have a radius, then Sphere
shouldn’t declare another r
(which will just hide the one in Shape
depending on the context from where it is named).If only a
Sphere
is supposed to have a radius, then it shouldn’t be possible to set r
through a ThreeDimentional
pointer, which ought to be agnostic about what kind of ThreeDimentional
object the pointer is pointing to. (In circumstances where a decision must still be taken based on the derived type nonetheless, dynamic_cast
can 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!