Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inheritance. Call child class function from parent class

Tags:

c++

oop

qt

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?

like image 468
Eddie Avatar asked Jul 27 '26 06:07

Eddie


2 Answers

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.

like image 58
Shahbaz Avatar answered Jul 29 '26 22:07

Shahbaz


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).

like image 20
Luchian Grigore Avatar answered Jul 29 '26 20:07

Luchian Grigore