0% found this document useful (0 votes)
12 views

OOP Pointers

This document discusses const qualifiers in C++ and valid/invalid assignments involving const-qualified variables and pointers. It also discusses how references to const variables behave, noting that assigning to a non-const reference of a const variable actually modifies a temporary variable rather than the const variable itself.

Uploaded by

al_badwi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

OOP Pointers

This document discusses const qualifiers in C++ and valid/invalid assignments involving const-qualified variables and pointers. It also discusses how references to const variables behave, noting that assigning to a non-const reference of a const variable actually modifies a temporary variable rather than the const variable itself.

Uploaded by

al_badwi
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

int i; int *ip; int * const cp = &i; const int ci = 7; const int *cip; const int * const cicp

= &ci;

// // // // // //

just an ordinary integer uninitialized pointer to integer constant pointer to integer constant integer pointer to constant integer constant pointer to constant integer

The following assignments are valid:


i = ci; *cp = ci; cip = &ci; cip = cicp; // assign constant integer to integer // assign constant integer to variable which is referenced by constant pointer // change pointer to constant integer // set pointer to constant integer to reference variable of constant pointer to constant integer // // // // // cannot change constant integer value cannot change constant integer referenced by pointer cannot change value of constant pointer this would allow to change value of constant integer *cip with *ip

The following assignments are invalid:


ci = 8; *cip = 7; cp = &ci; ip = cip;

When used with references some peculiarities must be considered. See the following example program:
int main() { const int ci = 1; const int &cr = ci; int &r = ci;

// create temporary integer for reference

// cr = 7; // cannot assign value to constant reference r = 3; // change value of temporary integer cout << "ci == << ci << r == " << r;

What actually happens is that the compiler automatically creates a temporary integer variable with value of ci to which reference r is initialized. Consequently, when changing r the value of the temporary integer is changed. This temporary variable lives as long as reference r. Reference cr is defined as read-only (constant reference). This disables its use on the left side of assignments.

You might also like