Cerin
Cerin

Reputation: 64820

How to store an instance reference in a class constructor

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

Answers (1)

songyuanyao
songyuanyao

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

Related Questions