CPP Pointers and const Modifier

Using const modifier with pointers.

  • In some cases, we do not want to pass a pointer to a method or function without any restriction.
  • In such a case and other cases, we may be use const modifier.
  • You can use the keyword const for pointers before the type, after the type, or in both places.
    const int * pNumber1;
    int * const pNumber2;
    const int * const pNumber3;
  • Each of these, however, does something different:
    1. pNumber1 is a pointer to a constant integer. The value that is pointed to can't be changed.
    2. pNumber2 is a constant pointer to an integer. The integer can be changed, but pNumber2 can't point to anything else.
    3. pNumber3 is a constant pointer to a constant integer. The value that is pointed to can't be changed, and pNumber3 can't be changed to point to anything else..
  • Class methods can be applied with the keyword const, which means that it makes a contract with the compiler that no class member variable shall be changed in that method.
  • In this case a pointer to a constant object can only use method in the class of the last kind.
    Here is an Example
    #include <iostream>
    using namespace std;
    class Distance {
    	int length ;
        int second ;
    public:
    	int getLength() const { return length; }
    	int getSecond() const { return second; }
    	Distance (int length,int second) {
    		this->length=length;
    		this->second=second;
    	}
    	~Distance () {
    		cout << "Distance object destroyed\n";
    	}
    };
    class Controller {
      const Distance *pdistances[20] ;
      int size;
    public:
    	Controller() {size=0; }
    	void addDistance( const Distance  * const pdist) {
    // In this method the value that pdist points to can't be changed, 
    // and pdist can't be changed to point to anything else.
           pdistances[size++]=pdist;
    	}
    	~Controller() {
    		for (int i=0 ; i<size ; i++) {
    			delete pdistances[i];
    		}
    	}
    	void listDistances() {
    		for (int i=0 ; i<size ; i++) {
    			cout << "Distance : " << pdistances[i]->getLength() ;
    			cout << " km on " << pdistances[i]->getSecond() << "\n";
    		}
    	}
    };
    int main() {
    	Controller * pController=new Controller();
        pController->addDistance(new Distance(3,9));
    	pController->addDistance(new Distance(5,19));
        pController->listDistances();
    	delete pController;
    }
    When we run this application the result could be:
    Distance : 3 km on 9
    Distance : 5 km on 19
    Distance object destroyed
    Distance object destroyed

    You can download this example here (needed tools can be found in the right menu on this page).

    Here is another example with the class Cylinder:
    The header file Cylinder.h:
    class Cylinder {
    public:
      Cylinder();
      ~Cylinder();
      void setRadius(int radius);
      int getRadius() const;
      void setHeight(int height);
      int getHeight() const;
    private:
      int radius;
      int height;
    };
    The Source file Cylinder.cpp:
    #include "Cylinder.h"
    
    // Implementation of the 
    // Constructor method in Cylinder class
    Cylinder::Cylinder() {
      radius = 2;
      height = 5;
    }
    // Implementation of the 
    // Destructor method in Cylinder class
    Cylinder::~Cylinder() {}
    
    // Implementation of the 
    // setRadius method in Cylinder class
    void Cylinder::setRadius(int radius) {
      this->radius = radius;
    }
    // Implementation of the 
    // getRadius method in Cylinder class
    int Cylinder::getRadius() const {
      return radius;
    }
    // Implementation of the 
    // setHeight method in Cylinder class
    void Cylinder::setHeight(int height) {
      this->height = height;
    }
    // Implementation of the 
    // getHeight method in Cylinder class
    int Cylinder::getHeight() const {
      return height;
    }
    The Application file AppCylinder.cpp:
    #include <iostream>
    #include "Cylinder.h"
    using namespace std;
    
    int main(){
      Cylinder * pCyl =  new Cylinder;
      const Cylinder * pConstCyl = new Cylinder;
      Cylinder * const pConstPtr = new Cylinder;
    
      cout << "pCyl height: " << pCyl->getHeight()
        << " meter"  << endl;
      cout << "pConstCyl height: " << pConstCyl->getHeight()
        << " meter" << endl;
      cout << "pConstPtr height: " << pConstPtr->getHeight()
        << " meter" << endl;
    
      pCyl->setHeight(10);
      // cannot change the object pConstCyl is pointing to
      // pConstCyl->setHeight(10);  //compiler error!
      pConstPtr->setHeight(10);
    
      cout << "pCyl height: " << pCyl->getHeight()
        << " meter"  << endl;
      cout << "pConstCyl height: " << pConstCyl->getHeight()
        << " meter" << endl;
      cout << "pConstPtr height: " << pConstPtr->getHeight()
        << " meter" << endl;
      return 0;
    }
    When we run this application the result will be:
    pCyl height: 5 meter
    pConstCyl height: 5 meter
    pConstPtr height: 5 meter
    pCyl height: 10 meter
    pConstCyl height: 5 meter
    pConstPtr height: 10 meter

    You can download this example here (needed tools can be found in the right menu on this page).

© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.