0

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?

3
  • Make b() a pure virtual function in Base. Commented Dec 26, 2016 at 19:34
  • Welcome to Stack Overflow. Please take the time to read The Tour and refer to the material from the Help Center what and how you can ask here. Commented Dec 26, 2016 at 19:34
  • With forward declaration, and split declaration from definition, your sample may work. But I am not sure that what you show is really what you want. Commented Dec 26, 2016 at 19:42

3 Answers 3

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();
 };
Sign up to request clarification or add additional context in comments.

4 Comments

You have to remember not to call such functions in constructor or desctructor, otherwise you'll end up with pure function call.
@paweldac Fortunately that's not the case in the OP's sample. If there's need to do so your answer fixes that problem.
just wanted to make it clear to other readers that might use proposed code. True that in OPs question, this error won't come up :)
@paweldac I'm out of votes for today, sorry. Otherwise I would have upvoted your answer.
0

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(); } 

1 Comment

It compiles, yes. Though I'm afraid that's not what's being asked here (as you mentioned in the comment).
0

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;
    }
};

1 Comment

That's another way to do it, yes.

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.