Saturday, April 19, 2025

C++ Multiple References, Pointers to References

Just as a person can have multiple nicknames, a variable can have multiple references to it.

First we will create a variable with value of 555, for example:

int var = 555;

Then three references to variable, using ampersand symbol in different places (yes, we can do that):

int& ref1 = var;
int & ref2 = var;
int  &ref3 = var;

Now we are printing value directly from a variable:

cout << "Direct value: " << var << endl;

And now using references:

cout << "Value using ref1: " << ref1 << endl;
cout << "Value using ref2: " << ref2 << endl;
cout << "Value using ref3: " << ref3 << endl;

Full script: 

#include <iostream>

using namespace std;

int main() {

    int var = 555;

    int& ref1 = var;
    int & ref2 = var;
    int  &ref3 = var;

    cout << "Direct value: " << var << endl;

    cout << "Value using ref1: " << ref1 << endl;
    cout << "Value using ref2: " << ref2 << endl;
    cout << "Value using ref3: " << ref3 << endl;

    return 0;

}

Result:

Direct value: 555
Value using ref1: 555
Value using ref2: 555
Value using ref3: 555

Process returned 0 (0x0)   execution time : 0.579 s
Press any key to continue.

Pointers to References

C++ is powerful language. We can have pointers to references.

First, variable setup:

int var = 555;

Then 3 references to original variable, using ampersand symbol:

//References
int& ref1 = var;
int & ref2 = var;
int  &ref3 = var;

Then 4 pointers. One for an original variable, three for references individually:

//Pointers
int *ptrVar = &var;
int *ptrRef1 = &ref1;
int *ptrRef2 = &ref2;
int *ptrRef3 = &ref3;

And now we can get memory address. 

cout << ptrVar << endl;
cout << ptrRef1 << endl;
cout << ptrRef2 << endl;
cout << ptrRef3 << endl;

And extract values:

cout << *ptrVar << endl;
cout << *ptrRef1 << endl;
cout << *ptrRef2 << endl;
cout << *ptrRef3 << endl;

Full source: 

#include <iostream>

using namespace std;

int main() {

    int var = 555;
    //References
    int& ref1 = var;
    int & ref2 = var;
    int  &ref3 = var;

    //Pointers
    int *ptrVar = &var;
    int *ptrRef1 = &ref1;
    int *ptrRef2 = &ref2;
    int *ptrRef3 = &ref3;
    
    cout << ptrVar << endl;
    cout << ptrRef1 << endl;
    cout << ptrRef2 << endl;
    cout << ptrRef3 << endl;

    cout << *ptrVar << endl;
    cout << *ptrRef1 << endl;
    cout << *ptrRef2 << endl;
    cout << *ptrRef3 << endl;

    return 0;

}

Result:

0x6dfed0
0x6dfed0
0x6dfed0
0x6dfed0
555
555
555
555

Process returned 0 (0x0)   execution time : 0.106 s
Press any key to continue.

No comments:

Post a Comment

Tkinter Introduction - Top Widget, Method, Button

First, let's make shure that our tkinter module is working ok with simple  for loop that will spawn 5 instances of blank Tk window .  ...