I have a program where two classes need each other in their Initialization process, but so far all I get is Compilation Error and I have no idea how to make it work
in Class MainComponent
class MainComponent : {
private:
PlaylistComponent playlistComponent{formatManager, *this};
}
in Class PlaylistComponent
class PlaylistComponent :{
private:
MainComponent& mainComponent;
}
PlaylistComponent::PlaylistComponent(juce::AudioFormatManager &_formatManager, MainComponent &_mainComponent):
formatManager(_formatManager),
mainComponent(_mainComponent){
//something else
}
and here are the error messages:
error: ‘MainComponent’ has not been declared
29 | PlaylistComponent(juce::AudioFormatManager&, MainComponent&);
error: ‘MainComponent’ does not name a type; did you mean ‘Component’?
74 | MainComponent& mainComponent;
error: ‘PlaylistComponent’ does not name a type; did you mean ‘MainComponent’?
49 | PlaylistComponent playlistComponent{formatManager, *this};
error: ‘MainComponent’ has not been declared
29 | PlaylistComponent(juce::AudioFormatManager&, MainComponent&);
error: could not convert ‘{((MainComponent*)this)->MainComponent::formatManager, (*(MainComponent*)this)}’ from ‘<brace-enclosed initializer list>’ to ‘PlaylistComponent’
49 | PlaylistComponent playlistComponent{formatManager, *this};
| ^
| |
| <brace-enclosed initializer list>
So far I have tried different approach such as " forward declarations"(Two classes that refer to each other) but it did not work, and the error message was that playlistComponent
has incomplete type PlaylistComponent
I know that it's because one Class needs to be initialized before the other, but how could I do this when both Classes need each other during the Initialization process?
CodePudding user response:
You need something like this(forward declaration: because you didn't show us how you used forward decleration I show that again here):
//in A.h file
class B;
class A{
B* b; // or anything else that dont need definition here and just need definition in cpp file.
}
//in B.h file
class A;
class B{
A* a; // or anything else that dont need definition here and just need definition in cpp file.
}
// in A.cpp
include "A.h"
include "B.h"
// in B.cpp
include "B.h"
include "A.h"
Note: always write the namespaces too if the class has namespace(in forward decleration) for example:
namespace mine{
class A;
}