Const member functions C++ example

Constant member functions in C++ class are declared using const keyword, for example, int fun() const. A constant member function of a class cannot modify any non-constant data members of the class and also cannot call non constant member functions.

For example, in below C++ program, function getProductId()is constant and hence, if try to modify any class data member e.g. pId or cost inside it or try to call any non static function then compiler will flash an error. Read comments in the C++ program example.


// const member function in C++ program
#include <iostream>
using namespace std;

class Product
{
      int pId;
      float cost;
      public:
            //constructor
            Product(int pId, float cost)
            {
                  this->pId = pId;
                  this->cost = cost;
            }

      /*---------------------------------------
      *Gettr and setter of class data members
      */
      //set product id
      void setProductId(int pId)
      {
            this->pId = pId;
      }  

      //This method cannot modify any
      //data member of this class
      //If we try to modify them then compiler
      //will flash an error l-value specifies
      //const object
      int getProductId()const
      {
            //if try to modify any data member
            // e.g. pId here the compiler will
            //flash error e.g.
            //this->pId = 20;//error

            //Also cannot call non static function
            //of this class in here e.g.
            //setProductId(50); error

            return pId;
      }    

      //Print data
      void print()
      {
             cout<<"Product Id : "<<this->pId;
             cout<<" Cost : "<<this->cost<<endl;
      }

};


int main()
{
      int pId = 1234;
      float cost = 100.00;
      Product p(pId,cost);  
      p.getProductId();
      p.print();           

      return 0;

}

Output:

Product Id : 1234 Cost : 100

NOTE:

If const member function of the class is defined outside of the class, then function declaration and definition both should contain const keyword like below C++ class example.


class Product
{
	int pId;
public:
	//constructor of the class 
	Product(int pId){this->pId = pId;}

	//declare the const member functions but
	//define it outside of the class
	int getProductId()const;	
};

//function definition. it should also 
//contain const keyword
int Product::getProductId() const{
	return pId;
}

Related Posts