const Pointers in C++

By: Lakshmi Emailed: 1705 times Printed: 2205 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

You can use the keyword const for pointers before the type, after the type, or in both places. For example, all of the following are legal declarations:


const int * pOne;
int * const pTwo;
const int * const pThree;

pOne is a pointer to a constant integer. The value that is pointed to can't be changed.

pTwo is a constant pointer to an integer. The integer can be changed, but pTwo can't point to anything else.

pThree is a constant pointer to a constant integer. The value that is pointed to can't be changed, and pThree can't be changed to point to anything else.

The trick to keeping this straight is to look to the right of the keyword const to find out what is being declared constant. If the type is to the right of the keyword, it is the value that is constant. If the variable is to the right of the keyword const, it is the pointer variable itself that is constant.

const int * p1;  // the int pointed to is constant
int * const p2;  // p2 is constant, it can't point to anything else

const Pointers and const Member Functions

When a function is declared const, the compiler flags as an error any attempt to change data in the object from within that function.

If you declare a pointer to a const object, the only methods that you can call with that pointer are const methods. Program below illustrates this.

Using pointers to const objects.


1:      // 
2:      // Using pointers with const methods
3:
4:      #include <iostream.h>
5:
6:      class Rectangle
7:      {
8:      public:
9:           Rectangle();
10:           ~Rectangle();
11:           void SetLength(int length) { itsLength = length; }
12:           int GetLength() const { return itsLength; }
13:
14:           void SetWidth(int width) { itsWidth = width; }
15:           int GetWidth() const { return itsWidth; }
16:
17:      private:
18:           int itsLength;
19:           int itsWidth;
20:      };
21:
22:      Rectangle::Rectangle():
23:      itsWidth(5),
24:      itsLength(10)
25:      {}
26:
27:      Rectangle::~Rectangle()
28:      {}
29:
30:      int main()
31:      {
32:           Rectangle* pRect =  new Rectangle;
33:           const Rectangle * pConstRect = new Rectangle;
34:           Rectangle * const pConstPtr = new Rectangle;
35:
36:           cout << "pRect width: " << pRect->GetWidth() << " feet\n";
37:           cout << "pConstRect width: " << pConstRect->GetWidth() << " feet\n";
38:           cout << "pConstPtr width: " << pConstPtr->GetWidth() << " feet\n";
39:
40:           pRect->SetWidth(10);
41:           // pConstRect->SetWidth(10);
42:           pConstPtr->SetWidth(10);
43:
44:           cout << "pRect width: " << pRect->GetWidth() << " feet\n";
45:           cout << "pConstRect width: " << pConstRect->GetWidth() << " feet\n";
46:           cout << "pConstPtr width: " << pConstPtr->GetWidth() << " feet\n";
47:      return 0;
48: }

Output: pRect width: 5 feet
pConstRect width: 5 feet
pConstPtr width: 5 feet
pRect width: 10 feet
pConstRect width: 5 feet
pConstPtr width: 10 feet

Analysis: Lines 6-20 declare Rectangle. Line 15 declares the GetWidth() member method const. Line 32 declares a pointer to Rectangle. Line 33 declares pConstRect, which is a pointer to a constant Rectangle. Line 34 declares pConstPtr, which is a constant pointer to Rectangle.
Lines 36-38 print their values.

In line 40, pRect is used to set the width of the rectangle to 10. In line 41, pConstRect would be used, but it was declared to point to a constant Rectangle. Therefore, it cannot legally call a non-const member function; it is commented out. In line 38, pConstPtr calls SetAge(). pConstPtr is declared to be a constant pointer to a rectangle. In other words, the pointer is constant and cannot point to anything else, but the rectangle is not constant.


C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(0)


Be the first one to add a comment

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Lakshmi
Exporting a Certificate Authenticating Your Public Key example using keytool in Java
while and do-while example in Java
Common SQL Commands
Data Access Technologies in Java
perror() Function - example program in C
Struts-GUI and Struts Console
Variable-length Argument Lists sample program in C
#if, #elif, #ifndef, #ifdef in C (Conditional Inclusion)
Use ImageButtonBean for Image based Form Submits in Struts
break and continue loops in C
Arguments - Call by Value in C
Using command-line arguments in C++
How to handle Exceptions in C++
Gauge sample program in J2ME
What is Reflection? - getConstructors(), getFields(), and getMethods()

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
Calculating total based on the given quantity and price in C++
Using cout.width() in C++
Using cout.fill() in C++
Programming errors a compiler will detect in C++
File in C++ - Writing text to a file in C++
assert() example program in C++
Using peek() and putback() with cin in C++
Lvalues and Rvalues in C++
Specifying default values to function parameters in C++
C++ Recursion function explained using Fibonacci series
Interface Versus Implementation in C++
C++ Sample Program for Allocating, using, and deleting pointers.
C ++ Reference Parameters Versus Java Reference Parameters
Converting C++ Multiple-Inheritance Hierarchies to Java
Printing values in DEBUG mode in C++
Most Emailed Articles (in C++)
A Brief History of C++
atoi(), itoa() in C++
Character String Literals in C++
Lvalues and Rvalues in C++
Advanced if Statements in C++
Passing parameters to a function by value in C++
class keyword in C++
continue and break statements in C++
do...while Loops in C++
C++ Sample Program for Allocating, using, and deleting pointers.
Converting Pointers that Operate on Arrays in C++ to Java
Converting C++ Multiple-Inheritance Hierarchies to Java
ctime() sample program in C++
Implementing Pure Virtual Functions in C++
Call by reference in C++ Functions