class C1 {
void A();
void B();
}
void C1::A(){ return B(); }
class C2 : public C1 {
void B();
}
C2 *obj = new C2;
obj->A(); // returns B() from C1
Why does B() from C1 called? How to make A() exist only in C1 and call B() from C2?
You need to make B() in C1 a virtual function.
Virtual functions are basically function pointers that take their value upon initialization of the object. If you new C1, the function pointer would point to C1::B while if you new C2 that function pointer would point to C2::B.
Note: To read more about virtual and related subjects, search for function overriding and polymorphism.
Member methods are not virtual by default in C++ (do you come from Java)?
When you write:
class C1 {
void A();
void B();
}
class C2 : public C1 {
void B();
}
you're not overriding B() in C2, but hiding it.
To override it, you must declare it virtual in the base class (virtual in subsequent classes is not necessary).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With