C++. References. Basic consepts. References to variables, structures, unions and class objects. Differences between references and pointers. Examples




References. Basic consepts. References to variables, structures, unions and class objects. Differences between references and pointers. Examples


Contents


Search other websites:

1. How to declare a variable reference? General form. Symbol ‘&’

When declaring, the reference should necessarily be initialized. In the simplest case of a reference is declared as follows:

type & ref_var = var;

where

  • type – the type to which the reference is declared;
  • ref_var – variable of type “reference” to ‘type’;
  • var – variable of ‘type’ type, to which the reference is declared.

2. Examples to declaring and using a reference to the variable, union and structure

Example 1. Declaring the reference named rd to the integer variable d.

int d; // a variable
int & rd = d; // reference named rd to the variable d, it is initialized when declaring

d = 0;
rd = 2; // d = 2

/*
int & rd2; // error (reference must be initialized when declaring)
*/

Example 2. Declaring a reference to a structure variable.

Let there be given a type of structure, which implements a date:

struct Date
{
    int day;
    int month;
    int year;
};

Then the use of reference to a structure variable of Date type can be as follows:

Date d;
Date & rd = d; // reference to the Date structure

// access to the structure fields using a reference
rd.day = 14; // d.day = 14
rd.month = 1; // d.month = 1
rd.year = 1972; // d.year = 1972

Example 3. Declaring and using reference to the union.

Let there be given a union TYPES.

union TYPES
{
    int d[2];
    char c[4];
    float x;
};

Demonstration and using the reference to the TYPES union.

TYPES t; // t - variable of type "union"
TYPES & rt = t; // reference to t
char c;
int d;

rt.c[0] = 'A';
c = t.c[0];

rt.d[1] = 28;
d = t.d[1];

3. What are the differences between reference and pointer?

Between reference and pointer are the following main differences:

  • the reference must be obligatorily initialized when declaring. The pointer does not need to be initialized when declaring. The pointer can also be assigned values after its declaration during the execution of the program;
  • after the reference is declared and initialized, this address can not be assigned to the addresses of other objects. The pointer can change its values as many as desired;
  • the pointer can be assigned a null value. It is impossible to assign a null value for reference;
  • when declaring an array of links, the compiler will report an error. You can declare an array of pointers.





4. How to declare a reference to an object of some class? Example of declaring and using

 Let there CFloat class be given. Class declares an internal variable of float type, constructors and access methods Get(), Set(). The example demonstrates the use of reference to the CFloat class object.

The program code of unit, created using “Win32 Console Application”, is as follows:

#include "stdafx.h"
#include <iostream>
using namespace std;

class CFloat
{
    float x;

    public:
    // class constructors
    CFloat() { x = 0; }
    CFloat(float nx) { x = nx; }

    // access methods
    float Get() { return x; }
    void Set(float nx) { x = nx; }
};

int _tmain(int argc, _TCHAR* argv[])
{
    // reference to the object of CFloat class
    CFloat f; // f - the object of CFloat class
    CFloat & rf = f; // rf - reference to the CFloat class object
    float x;

    rf.Set(5.5); // access to the class methods using reference
    x = f.Get(); // x = 5.5
    f.Set(-8.2);
    x = rf.Get(); // x = -8.2
    return 0;
}

5. Is it possible to declare a reference to ‘void’ type? Is there a type of ‘void&‘?

No.

6. Is it possible to change the value by reference if it is declared with the keyword const (declared as constant)?

No.

7. How to use a reference to pass a variable (object of a class) into a function? Example

Using a reference it is possible to pass a variable or pass an class object into a function. Thus, in the body of the function, you can change the value of the passed variable.

Example 1. Demonstration of passing a variable of type int to a function and changing its value in the body of a function. The “Win32 Console Application” type of project.

#include "stdafx.h"
#include <iostream>
using namespace std;

// Function Inc5() - increases by 5
void Inc5(int & t) // passing t by reference
{
    t += 5;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int d;
    d = 5;
    Inc5(d); // d = 10
    Inc5(d); // d = 15
    return 0;
}

Example 2. The example demonstrates passing a class object by reference. Let there CRadius class and function Volume() be given. The object of CRadius class is passed by reference into Volume() function.

Passing a class object by reference is more efficient than passing by value. Since when passing an object by value, all object data is copied to the stack. If there is a lot of data in the object, this greatly increases the execution time when the function is called.

The program text, created using the template “Win32 Console Application“:

#include "stdafx.h"
#include <iostream>
using namespace std;

class CRadius
{
    double radius;

    public:
    // constructors
    CRadius() { radius = 1; }
    CRadius(double nradius) { radius = nradius; }

    // access methods
    void Set(double nradius) { radius = nradius; }
    double Get() { return radius; }
};

// calculates the volume of a sphere
double Volume(CRadius & R) // pass parameter by a reference
{
    double vol, radius;
    radius = R.Get();
    vol = 4.0 / 3.0 * 3.1415 * radius * radius * radius;
    return vol;
}

int _tmain(int argc, _TCHAR* argv[])
{
    CRadius r(2.5); // instance of CRadius class
    double vol;
    vol = Volume(r); // passing a class object by reference
    cout << vol << endl; // vol = 65.4479
    return 0;
}

8. How do I return a reference from a function? Examples

A function can return a reference to an object. In this case, the function call can be placed on the left side of the assignment operator (see example 2).

Example 1. The returning from the function using a reference to the int type is demonstrated.

#include "stdafx.h"
#include <iostream>
using namespace std;

// returning the reference from function
int & Inc5(int t) // function increases by 5 the value of the parameter t
{
    t = t + 5;
    return t;
}

int _tmain(int argc, _TCHAR* argv[])
{
    int a, b;
    b = 7;
    a = Inc5(b); // a = 12
    cout << a << endl;
    return 0;
}

Example 2. The change in the value of the external (global) array A is demonstrated with the Change() function, which returns a reference to the item of array A with the given index.

The text of the demo program created using the Win32 Console Application template is as follows

#include "stdafx.h"
#include <iostream>
using namespace std;

#define MAX 20
double A[MAX];

// the function, which returns a reference to the item of array A with a given index
double & Change(int index)
{
    // return the value of the item of array A
    return A[index];
}

int _tmain(int argc, _TCHAR* argv[])
{
    int i;

    // array filling
    for (i=0; i<MAX; i++)
        A[i] = i * 2; // A = { 0.0, 2.0, 4.0, ..., 38.0 }

    // changing the value of an array item with index 5 using the function
    ChangeA(5) = 3.25; // A[5] = 3.25;
    ChangeA(MAX-1) = -7.77; // A[19] = -7.77;
    return 0;
}

9. Examples of initializing a structured variable using references

The two ways of initializing a structure variable.

Example 1. Returning the reference to the structure variable. Initialization of the structural variable is implemented in the function InitPixel().

#include "stdafx.h"
#include <iostream>
using namespace std;

// the pixel structure
struct Pixel
{
    int x, y, color;
};

// function that returns a reference to structure Pixel
Pixel & InitPixel(int value)
{
    Pixel px;
    px.x = px.y = px.color = value;
    return px;
}

int _tmain(int argc, _TCHAR* argv[])
{
    Pixel px;
    Pixel px2 = InitPixel(5); // px2.x = 5; px2.y = 5; px2.color = 5;
    px = InitPixel(11); // px.x = 11; px.x = 11; px.x = 11;
    cout << px.x << " - " << px.y << " - " << px.color << endl;
    cout << px2.x << " - " << px2.y << " - " << px2.color << endl;
    return 0;
}

Example 2. Initializing a structure variable of Pixel type. The function InitPixel() receives a reference to the structure variable as a parameter.

#include "stdafx.h"
#include <iostream>
using namespace std;

// the Pixel structure
struct Pixel
{
    int x, y, color;
};

// function that returns a reference to the Pixel structure
void InitPixel(Pixel & px, int x, int y, int color)
{
    // changing the value of structure variable into a function
    px.x = x;
    px.y = y;
    px.color = color;
    return;
}

int _tmain(int argc, _TCHAR* argv[])
{
    Pixel px;
    Pixel px2;
    InitPixel(px, 3, 8, 10); // px.x = 3; px.y = 8; px.color = 11;
    InitPixel(px2, 5, 5, 8); // px2.x = 5; px2.y = 5; px2.color = 8;
    cout << px.x << " - " << px.y << " - " << px.color << endl;
    cout << px2.x << " - " << px2.y << " - " << px2.color << endl;
    return 0;
}

10. What are the restrictions when working with references in C++?

In C++ the working with references has following restrictions:

  • references can not link to other references;
  • there is no null reference;
  • references must be initialized when they are declared.


Related topics