Cavya
Cavya

Reputation: 27

Calling derived class method in base class

We can call "Base class methods" in derived class. but Can we call derived class method in base class function?

#include<iostream.h>

class base {

 public:

   void print()
   {
     cout<<"base class";
   }

};

 class derived : public base

 {

  public:
    void print()
    {

            cout<<"derived class";

    }

 };

How to call this derived class print() function in Base class?

Upvotes: 2

Views: 7283

Answers (3)

songyuanyao
songyuanyao

Reputation: 172864

You can call derived class's method from base class method on a derived class object, if it's a virtual method:

class base {
  public:
    void doSomething() { 
      print();  
    }
    virtual void print() {
      cout<<"base class";
    }
};

class derived : public base {
  public:
    virtual void print() {
      cout<<"derived class";
    }
};

int main() {
  derived d;
  base* pb = &d;
  pb->doSomething();
}

It is known as Template method pattern.

Upvotes: 2

Mankarse
Mankarse

Reputation: 40613

If you know for certain that all instantiations of base will be as the base class of derived (as might be the case in a use of the Curiously Recurring Template Pattern), you can simply static_cast this to derived*:

#include <iostream>

class base {
public:
    void call_derived_print();
    void print()
    {
        std::cout<<"base class";
    }
};

class derived : public base
{
public:
    void print()
    {
       std::cout<<"derived class";
    }
};

void base::call_derived_print() {
    //undefined behaviour unless the most-derived type of `*this`
    //is `derived` or is a subtype of `derived`.
    static_cast<derived*>(this)->print();
}

Upvotes: 0

Rakib
Rakib

Reputation: 7615

You cannot call a normal method defined in derived class from base class. What you can do is add a virtual (possibly pure) method in base class, provide implementation in derived class. You can call this method from base.

class Base{
public:
 virtual void foo(){cout<<"Hello";};
 void bar() { foo();}
};

class Derived: public Base{
 public:
 void foo() override{ cout<<"Hi";}
};

int main() {
 Base* b1 = new Derived();
 b1->bar(); //will call Derived::foo()

 Base* b2=new Base();
 b2->bar(); // will call Base::foo()
}

Upvotes: 4

Related Questions