user1335175
user1335175

Reputation: 189

C++ reference to the class

I am new to c++ and I have a project where one of the classes have a reference to another class in the form that I will mention below. I just want to understand what reference to a class actually mean. Sorry, I am not going to post my program but rather just gonna provide an example, because I want to actually understand what reference to a class means instead of someone showing how to fix my code.

so lets say I have two classes Class_1 and Class_2. I need to call Class_1 from Class_2 by passing two arguments to Class_1`s constructor.

This is how Class_1 constructor looks like in a Class_1 cpp file

Class_1::Class_1(int nRows, int nCols)
{
    m_rows=nRows;
    m_cols=nCols;
    m_numSnakesDied=0;
    display();

}

It is a requirement for me to declare Class_2 in Class_1 header file in a following way

Class_1& class_1();

As you can see, I need to acquire nRows and nCols from Class_1 when it callls Class_2. The problem is that I don't understand what this Class_1& class_1(); actually means, and I am not sure how to initialize Class_1s constructor from Class_2s cpp file.

Sorry if my explanation is crappy, English is a third language to me.

Thank you.

Upvotes: 0

Views: 152

Answers (1)

Ruei-Min Lin
Ruei-Min Lin

Reputation: 89

It's kind of unclear for your question.

You can use something like:

Class_1 a; // a is an instance of Class_1
Class_1& b = a; // b is a reference to an instance of Class_1 (a)

so that a and b are exactly the same object.

If you need arguments for constructor:

Class_1 c(2, 3); // c is an instance of Class_1.
                 // this will initialize c with nRows = 2 and nCols = 3
Class_1& d = c;  // d is a reference to an instance of Class_1 (c)

As for your sample code:

Class_1& class_1();

It means class_1 is a function which returns a reference to an instance of Class_1. So maybe you want to implement something like:

Class_2 {
public:
    Class_1& class_1() {
        return a; // return a reference to an instance of Class_1 (a)
    }
private:
    Class_1 a; // an instance of Class_1
}

I suggest you to post more complete code so that we can help. Otherwise we are just guessing what's your problem.

Edit Remove the example of reference to a temporary because it's not permitted.

Upvotes: 1

Related Questions