4

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.

2 Answers 2

21

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Thx, now I know what the 'virtual' thing was... :D
Actually, virtual is THE feature that makes real OOP possible in C++.
Yeah, well... at least the inheritance part of it... imio (in my ignorant opinion), OOP would still be practical just using compositions...
@huff: True. virtual isn't exactly the enabling idiom as far as OOP goes, precisely. virtual makes polymorphism possible, which is one part of OOP.
5

Declare f2() as virtual.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.