• python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Facebook Twitter Instagram
Devs Fixed
  • python
  • javascript
  • reactjs
  • sql
  • c#
  • java
Devs Fixed
Home ยป Resolved: C++ Problem with overriding base class variable

Resolved: C++ Problem with overriding base class variable

0
By Isaac Tonny on 16/06/2022 Issue
Share
Facebook Twitter LinkedIn

Question:

I have 3 classes that derive from each other:
In 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!

c++
Share. Facebook Twitter LinkedIn

Related Posts

Resolved: How to set consistent decimal separators in R data frame?

26/03/2023

Resolved: How to resolve LNK2001 in c++ projects

26/03/2023

Resolved: How to correctly initialize vector of number in Typescript

26/03/2023

Leave A Reply

© 2023 DEVSFIX.COM

Type above and press Enter to search. Press Esc to cancel.