Inheritance. Call child class function from parent class
17,354
Solution 1
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.
Solution 2
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).
Comments
-
Eddie almost 2 years
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?