Krishna
Krishna

Reputation: 1382

Declare reference to class as class member

I want to declare a reference to class as similar to pointer to class as its own member variable. Following is the code I have written, but I am now stuck how to proceed further to create object of such a class, since the compiler will always give error even if I wrote default constructor or constructor to initialize only var.

class Test2
{
private:
    Test2& testRef;
    int var;

public:
    Test2( int x, Test2 testObj ) : var( x ), testRef( testObj )
    {

    }
};

What I need to do further to create object of such class or is simply not possible to do so. If not possible why not the compilers simply gives an error saying you can't have reference to the own class.

Upvotes: 1

Views: 3932

Answers (2)

Benjamin Lindley
Benjamin Lindley

Reputation: 103713

If you have a reference member, you have to initialize it in all constructors, because a reference must be initialized. Even your default constructor. Since the first object of such a class you create will not have anything else it can refer to, you will have to refer it to itself. For example:

Test2() :testRef(*this) {}

Upvotes: 5

Caduchon
Caduchon

Reputation: 5201

You try to pass a temporary copy of your object to the reference. If you pass the reference in the constructor, it will be ok :

Test2( int x, Test2& testObj ) : var( x ), testRef( testObj )
{

}

Additional question : do you need your reference non const ? It's probably better to use a const reference to your object if you don't modify it :

class Test2
{
  private:
    const Test2& testRef;
  public:
    Test2( int x, const Test2& testObj ) : var(x), testRef(testObj) {}
};

private: Test2& testRef; int var;

public: Test2( int x, Test2 testObj ) : var( x ), testRef( testObj ) {

}

};

Moreover, you should initialize in the same order than declared :

Test2(int x, const Test2& testObj) : testRef(testObj), var(x) {}

Upvotes: 0

Related Questions