Please help, some basic problems of C++

Sorry, i know this is pretty much a deficiency in my c++ knowledge, but i’m stuck here:

I have 2 files, MainComponent.h and MainComponent.cpp and Child.h and Child.cpp. I can initialize the Child class in MainComponent.h and use the variables and functions of Child, but I don’t know how to initialize it in Child.h. MainComponent’s class calls variables and functions in MainComponent class

This is my MainComponent.h initializing the Child class

#pragma once
#include "Child.h"
class MainComponent:public Component, public Button::Listener
{
public:
    MainComponent() ;
    ~MainComponent() ;
    
    void resized() override {  }
public:
//Initialize Child class of Child.h
    Child child;
}

This is my Child.h, how to initialize the MainComponent class in Child.h to use its variables and functions

#pragma once
#include "Child.h"
class Child:public Component, public Button::Listener
{
public:
    Child() ;
    ~Child() ;
    
    void resized() override {  }
public:

  
}

If you can avoid it architecturally, then don’t. But it is relatively common to have a back link.
Here is how you do it:

#pragma once
#include "Child.h"
class MainComponent:public Component, public Button::Listener
{
public:
    MainComponent() ;
    // ...
private:
    Child child { *this }; // <= create with dereferenced this as argument
}

And the Child:

#pragma once

class MainComponent; // <= forward declaration, only include MainComponent.h in your cpp

class Child:public Component, public Button::Listener
{
public:
    Child (MainComponent& owner) ;
    // ...
private:
    MainComponent& owner; // <= back link reference  
}

And the constructor in Child.cpp:

#include "Child.h"
#include "MainComponent.h"

Child::Child (MainComponent& ownerToUse) : owner (ownerToUse)
{
    // ...
}
4 Likes

Since @lggcyy says they have limited C++ knowledge I thought might be worthwhile explaining why this is necessary.

If MainComponent.h includes Child.h, and Child.h tries to include MainComponent.h, this causes a circular include and the compiler will bork due to essentially an infinite loop.

The forward declaration just lets Child.h know “there is a class MainComponent, but you don’t need to know much about it other than it exists”.

Then in Child.cpp you include MainComponent.h so that it knows about what methods/members are available when accessing owner.

3 Likes

@daniel @asimilon Thank you asimilon and daniel for your patience and help, that was really great, thanks!

I’d also like to offer my thanks to @daniel and @asimilon for clearing this forward declaration thing up. I´d been trying to implement daniel’s suggested “templated engine class” from here:

processBlock with float vs double? - Audio Plugins - JUCE

But this:

I just knew it was the includes, but somehow couldn’t quite find the right combo - so thank you again guys for the extra clarity! :slight_smile:

1 Like