Reputation: 124
I want to do something like this.
#include <iostream>
using namespace std;
class Instance {
public:
const string ClassName = "Instance";
string Name = ClassName;
bool Archivable = true;
Instance Parent;
};
int main() {
Instance obj1;
Instance obj2;
obj2.Parent = obj1; // set the parent instance to obj1
obj2.Parent.Name = "NewName"; // change the parent’s (obj1) name to “NewName”
cout << obj1.Name; // I want “NewName” to be printed out.
}
The problem is that I get an error, and I don’t know how to store objects as references.
Upvotes: 0
Views: 72
Reputation: 1599
You're not storing a reference but a value, so basically it is going to copy the value of obj1
into obj2.Parent
. So when you change obj2.Parent
's value you update the nested object which is not a reference to the true parent.
You have a few ways to manage ownership of nested elements which all depends on the context.
You could store a pointer:
Instance *Parent;
You could store a reference, which is almost the same thing, but quite uncommon in my experience:
Instance &Parent;
The easiest and best way would be to store a smart_pointer:
std::unique_ptr<Instance> Parent;
Edit, a working example:
#include <iostream>
using namespace std;
class Instance {
public:
const string ClassName = "Instance";
string Name = ClassName;
bool Archivable = true;
Instance *Parent;
};
int main() {
Instance obj1;
Instance obj2;
obj2.Parent = &obj1; // set the parent instance to obj1
obj2.Parent->Name = "NewName"; // change the parent’s (obj1) name to “NewName”
cout << obj1.Name << endl; // I want “NewName” to be printed out.
}
Upvotes: 1