Good day. Using the example of this, I want to understand how to make changes to a function of a class-successor. When calling class A, it should be 4, when calling B, it should be 8, but the output in both classes is 4. I can’t figure out how to fix the error.

#include <iostream> using namespace std; class A { public: int calculate() { return 2 * 2; } void print() { cout << calculate() << endl; } }; class B :public A { public: int calculate() { return 2 * 2 * 2; } }; void main() { A one; one.print(); B two; two.print(); } 
  • This is the same situation when you started learning a language, and you already needed what is usually learned a little later?) And can I scold you a little? Thank you) - isnullxbh
  • @isnullxbh, yes, yes, it turned out in the next chapter) let's - User
  • changed my mind)) ahah)) because you wrote this code for the sake of example?) - isnullxbh
  • @isnullxbh, yes, just to understand the principle) - User

1 answer 1

To correct the error, you can declare the function int calculate() as virtual in the base class, that is, virtual int calculate() .