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

。_饼干妹妹 提交于 2020-01-01 12:01:32

问题


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

Ex.

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 taking a wrong approach. Any comment about different designs around would also be appreciated.


回答1:


Declare f2() virtual in the base class.

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

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




回答2:


Declare f2() as virtual.



来源:https://stackoverflow.com/questions/2116782/c-inheritance-calling-a-derived-function-from-the-base-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!