Link to home
Start Free TrialLog in
Avatar of perlperl
perlperl

asked on

member variable reference

Is there any issue with this code. Can I have member variable reference in this way.
class A_1 {
 public:  
    A_1(A_2& obj) : _obj_2 ( obj) { }
    A_2& _obj_2;
};

class A_2 {
    A_1 _obj_1;
};

A_2::A_2()  : 
    _obj_1 (*this)
{ }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of jkr
jkr
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
The only problem I see is with class A_2. Here is your code:
class A_2 {
    A_1 _obj_1;
};

A_2::A_2()  : 
    _obj_1 (*this)
{ }

Open in new window

In class A_2 there is a member variable A_1 _obj_1, but there is no default constructor for A_1. I believe you code will not even compile, as A_1 class cannot be instantiated using A_1 _obj_1.

I think you need create a pointer variable inside your class A_2, like this:
class A_2 {
    A_1 *_obj_1;
};

A_2::A_2()
{
 _obj_1 = new A_1(*this);
}


A_2::~A_2()
{
 delete _obj_1;
}

Open in new window

the code compiles at my system (win7 vc++ vs2012) when a forward declaration of class A_2 was added such that the reference member can be defined in class A_1, and when the default constructor of A_2 not only was defined but also was declared in class A_2.

Sara
Avatar of pepr
pepr

Sara is right. @chaau, there is no need for default constructor of A_1 because it is not used. The only construction of the A_1 object is done inside the A_2 instance, and it is done via the non-default constructor. I believe, the identifiers below make it more readable (A_1 changed to A, A_2 changed to B, and the member variables accordingly):
class B;    // as Sara wrote

class A {
public:  
     A(B& obj) : _b(obj) { }
     B& _b;
};

class B {
public:     // added
    B();    // as Sara wrote
    A _a;   // is initialized via the B default-constructor initializer-list
};

B::B(): 
  _a(*this)  // here the non-default constructor is used
{ 
}
                                  
                                  
int main() {
    B b;
    return 0;
}

Open in new window

Notice that public: must also be added to the class B; otherwise, the members are considered private, including the declared B() default constructor. The B instance could not be conctructed without the public.
Avatar of perlperl

ASKER

Please ignore my syntax and constructor :)
Usually I try to shorten the code and only focus on the key thing like I just wanted to verify if there is any issue with reference member variable

Thanks everyone