Reputation: 64820
How do you pass in an instance reference to a class constructor and store that reference to a private variable?
I'm doing:
class MyClass{
private:
OtherClass obj;
public:
MyClass(OtherClass &_obj){
obj = _obj;
}
};
Upvotes: 1
Views: 1225
Reputation: 172994
You can make obj
a reference member. And you have to use member initialize list to initialize it since reference member can't be default-initialized.
class MyClass {
private:
OtherClass& obj;
public:
MyClass(OtherClass &_obj) : obj(_obj) {}
};
Note you need to guarantee the reference won't become invalid during the object's lifetime.
Upvotes: 5