Search code examples
c++inheritanceforwarding

Use a child function in a parent class cpp


I have a parent class and a child class where the parent class uses one of the child classes in one of the parent's methods. In this method the parent uses the constructor and a method (that is a virtual method inherited from the parent) of the child, I saw another question similar to this on stackoeverflow but they did not use use methods and constructors of the child (one person mentioned the problem was easier because they only used variables of the child-class). I tried some basic class forwarding in the parent (putting class child; at the top) and that did not work.

This is the set up without any public private distinctions an attempt at address the required headers:

//foo.h
class Foo{
    int x;
    Foo(int i);
    virtual void funA ();
    void funB();
};

//foo.cpp
Foo::Foo(int i) {
   x = i;
}
Foo::funA(){cout<<"Foo funA"<<endl;}
Foo::funB(){
    Bar b = Bar();
    b.funA();
}

//bar.h
class Bar : public Foo {
    Bar(int i);
    virtual void funA ();
};

//bar.cpp
Bar::Bar(int i) { x = i };
void Bar::funA(){cout<<"Bar funA"<<endl;}

I seem to be stuck on getting a the class forwarding to work. If someone could tell me how to set up my includes and class forwards that would be great!


Solution

  • Foo.h

    class Foo {
        int x;
        Foo(int i);
        virtual void funA();
        void funB();
    }
    

    Foo.cpp

    #include "Foo.h"
    #include "Bar.h"
    
    ...
    void Foo::funB() {
        Bar b();
        b.funA();
    }
    ...
    

    Bar.h has a dependency on Foo.h but you don't need any forward-declaration of classes (e.g. when you have a line like class Foo; that doesn't define a class body), just normal declarations. This is because Foo is not used by Bar's interface, only its implementation, so your Bar.h file can remain unchanged.