C ++ Inheritance, calling a derived function from a base class

How can I call a derived function from a base class? I mean, I can replace one function from the base to the derived class.

Ref.

class a { public: void f1(); void f2(); }; void a::f1() { this->f2(); } /* here goes the a::f2() definition, etc */ class b : public a { public: void f2(); }; /* here goes the b::f2() definition, etc */ void lala(int s) { a *o; // I want this to be class 'a' in this specific example switch(s) { case 0: // type b o = new b(); break; case 1: // type c o = new c(); // y'a know, ... break; } o->f1(); // I want this f1 to call f2 on the derived class } 

Maybe I'm wrong. Any comments about various designs will also be appreciated.

+4
source share
2 answers

Declare f2 () virtual in the base class.

 class a { public: void f1(); virtual void f2(); }; 

Then, whenever a derived class overrides f2() , a version will be called from the derived class itself, depending on the type of the actual object that the pointer points to, not the type of the pointer.

+20
source

Declare f2 () as virtual .

+5
source

Source: https://habr.com/ru/post/1299096/


All Articles