C++. References to the class object. Access to a class object by reference. References as members of class data. Examples




References to the class object. Access to a class object by reference. References as members of class data. Examples


Contents


Search other websites:

1. How is the variable declared, which is a reference to the class? How to declare a reference to a class object?

A reference to a class is declared using the ‘&’ symbol. When declaring a variable, which is a reference, you must immediately initialize it with the value of the object for which you already allocated memory.

The general form of the declaration of a reference to a class object is:

CMyClass & ref = obj;

where

  • CMyClass – class name;
  • ref – the name of the variable, which is a reference to the obj object;
  • obj – the name of the object for which memory is allocated.

2. Example of declaring a reference to a class object and using it

Let the class CYear, realizing the year, be given. The class declaration has the following form:

// class that implements the category "Year"
class CYear
{
    int year; // internal variable

    public:
    CYear(void); // default constructor

    // constructor with 1 parameter
    CYear(int year)
    {
        this->year = year;
    }

    // access methods
    int Get(void) { return year; }
    void Set(int year) { this->year = year; }

    // a method that determines a leap year or not
    bool IsLeapYear(void);
};

// default constructor
CYear::CYear(void)
{
    year = 2000; // initialization
}

// a method that determines a leap year or not
bool CYear::IsLeapYear(void)
{
    if (year % 400 == 0)
        return true;
    else
        if (year % 100 == 0)
            return false;
        else
            if (year % 4 == 0)
                return true;
            else
                return false;
}

Using a class in another method

CYear c1; // c1 - object,
CYear & c2 = c1; // c1 and c2 point to the same memory location
int d;

// access to object c1
c1.Set(2010); 
d = c1.Get(); // d = 2010

// access by reference c2
d = c2.Get(); // d = 2010
c2.Set(3333);
d = c1.Get(); // d = 3333; c1 and c2 point to the same memory location

In the above code, use the & symbol to declare the reference variable c2 for an object of class c1 using the following line

CYear & c2 = c1;

For c1 variable, memory is already allocated. The variables c1 and c2 refer to the same memory location (to the same object).

3. Declaring and using a reference to a class object accessed through an unmanaged pointer. Example

If you declare a pointer to a class (*) and allocate memory for it, then you can declare the reference to this memory location (object).

The following example demonstrates the use of a pointer and a reference to the CYear class, as described in paragraph 2.

CYear * pc = new CYear(); // unmanaged pointer, memory is allocated
CYear & rc = (*pc); // reference to the memory allocated for the pointer

int d;

// access to the object using the pointer
pc->Set(2040);
d = pc->Get(); // d = 2040
d = rc.Get(); // d = 2040
rc.Set(2100);
d = pc->Get(); // d = 2100

4. An example of using a reference to a class object that is a member of data of another class. What happens if you do not initialize a reference to an object in a class?

A reference (reference variable) to a class object can be a member of data of another class. When declaring a reference variable in a class, this variable can be initialized in a specially designed constructor. In this case, the memory is allocated dynamically for the class reference variable (see the example below).

The following example demonstrates the use of the CLine class (a segment) in which two references to the CPoint class are declared that describe a point on the coordinate plane.

The CPoint class implements the following data members and methods:

  • internal variables x, y – coordinates of the points;
  • default constructor;
  • access methods GetXY(), SetXY().

The CLine class declares the following data members and methods:

  • internal reference variables of type CPoint& (reference to a CPoint class object) with the names p1, p2;
  • a two-parameters constructor that dynamically initializes the references p1, p2 when declaring a class object;
  • access methods GetPoints(), SetPoints().





Declaring classes CPoint and CLine is as follows:

// a class that implements point
class CPoint
{
    int x,y;

    public:
    // default constructor
    CPoint() { x = y = 0; }

    // access methods
    void GetXY(int* nx, int* ny)
    {
        *nx = x;
        *ny = y;
    }

    void SetXY(int nx, int ny)
    {
        x = nx;
        y = ny;
    }
};

// a class that implements a segment
class CLine
{
    // references to the objects of CPoint type
    CPoint & p1;
    CPoint & p2;

    public:
    // default constructor
    // the values of references p1 and p2 are dynamically initialized
    CLine():p1(* new CPoint), p2(* new CPoint)
    {
        p1.SetXY(0, 0);
        p2.SetXY(1, 1);
    }

    // access methods
    // get the coordinates of points
    void GetPoints(CPoint* pt1, CPoint* pt2)
    {
        int x, y;
        p1.GetXY(&x, &y); // take the values of x, y for point p1
        pt1->SetXY(x, y); // set x, y to a new point pt1
        p2.GetXY(&x, &y); // take of x, y
        pt2->SetXY(x, y); // save x, y in pt2
    }

    // set a new points values
    void SetPoints(CPoint* pt1, CPoint* pt2)
    {
        int x, y;

        // p1 => pt1
        p1.GetXY(&x, &y);
        pt1->SetXY(x, y);

        // p2 => pt2
        p2.GetXY(&x, &y);
        pt2->SetXY(x, y);
    }
};

Important: when declaring a references to an object of a certain class, it is necessary to initialize these references with a certain value, for example, in a specially designed default constructor. If you do not specify the reference initialization code in the constructor, the compiler will generate an error:

p1' : must be initialized in constructor base/member initializer list ...

In the CLine class, the links p1 and p2 are dynamically initialized using the constructor:

// dynamic initialization of reference variables p1, p2 of class CLine
CLine():p1(* new CPoint), p2(* new CPoint)
{
    // ...
}

Using the CLine class in another method:

// reference to objects as a data members of class
CLine cl1; // a constructor is invoked, that initializes the reference-variables p1, p2

// additional variables
CPoint point1, point2;
int x, y;

// check how the constructor filled the coordinates of the points of a line segment
cl1.GetPoints(&point1, &point2);
point1.GetXY(&x, &y); // x = 0; y = 0
point2.GetXY(&x, &y); // x = 1; y = 1

// set a new values
point1.SetXY(3, 8); // save the point (3; 8)
point2.SetXY(5, 9); // save the point (5; 9)
cl1.SetPoints(&point1, &point2);

// test
CPoint pp1, pp2;
cl1.GetPoints(&pp1, &pp2);
pp1.GetXY(&x, &y); // x = 3; y = 8
pp2.GetXY(&x, &y); // x = 5; y = 9


Related topics