I'm trying to split some functionality between multiple .cpp files and I've got an issue. Let's say, I have:
Extra.h
#include "CustomClass.h"
namespace extraSpace
{
extern int justInteger;
extern CustomClass *complexObject;
}
Extra.cpp
include "Extra.h"
int extraSpace::justInteger = 1;
CustomClass *extraSpace::complexObject = new CustomClass;
complexObject->SomeProperty = 1; // Can't do this
Main.cpp
include "Extra.h"
int main()
{
std::cout << extraSpace::justInteger << "\n";
std::cout << extraSpace::complexObject->SomeProperty << "\n";
}
This code works well for justInteger
variable. However, I cannot manipulate complexObject
properties in Extra.cpp
. Is there any simple workaround here?
I thought about creating some InitObject()
function, but this would mean that I would have to change the object from Main.cpp
, which I would rather not do.
CodePudding user response:
CustomClass *extraSpace::complexObject = new CustomClass;
complexObject->SomeProperty = 1; // Can't do this
You can use a lamda.
CustomClass *extraSpace::complexObject = [] {
auto* complexObject = new CustomClass;
complexObject->SomeProperty = 1;
return complexObject;
}();