Mattia Urru
Mattia Urru

Reputation: 1

Inheritance : call a derived class function from base class

Is possible in C++ to make this?

class Base {
     int a(Derived d) { d.b(); } 
 };

 class Derived : public Base {
    int b();
 };

Should i include Derived.hpp even in Base.hpp?

Upvotes: 0

Views: 70

Answers (3)

paweldac
paweldac

Reputation: 1184

It's possible to call functions from Derived class from Base class with C++ idiom called: "Curiously recurring template pattern" CRTP. Please find call below:

template <class Child> 
struct Base
{
    void foo()
    {
        static_cast<Child*>(this)->bar();
    }
};

struct Derived : public Base<Derived>
{
    void bar()
    {
        std::cout << "Bar" << std::endl;
    }
};

Upvotes: 0

πάντα ῥεῖ
πάντα ῥεῖ

Reputation: 1

Is possible in C++ to make this?

Yes, it's very easy and a basic pattern (called polymorphism or Template Method Pattern) used in the c++ language:

class Base {
     int a() { b(); } // Note there's no parameter needed!
// Just provide a pure virtual function declaration in the base class
protected:    
     virtual int b() = 0;

 };

 class Derived : public Base {
    int b();
 };

Upvotes: 1

Jarod42
Jarod42

Reputation: 218238

The following compiles:

class Derived;

class Base {
public:
    int a(Derived d);
};

class Derived : public Base {
public:
    int b() { return 42; }
};

int Base::a(Derived d) { d.b(); } 

Upvotes: 0

Related Questions