C++ Constants

October 27, 2015 Posted by WithU Technologies
Constant is an expression with a fixed value assigned to it and it cannot be changed until program terminates.

In case of constants we use the const keyword before the datatype during declaration of a variable.
const int x = 25;

const variables must be initialised during creation as we initialised here with 25.

Const Objects:

int main(){
      const NewClass NewOb;  //New constant Object is created

}

·         In case of classes, initialization is done via constructor. We can either use a parametrized constructor or a public default constructor.

·         After declaring const objects, we can change its data members value during the object’s lifetime.

·         Non-Constant objects can call non-constant functions.

·         And to call constant objects, we need constant functions.

·         Constant member functions cannot modify any non-constant data members.

·         So, a const keyword is to be used with the functions in both header (.h) and source file (.cpp).

·         The const keyword follow the function prototype, after the parenthesis.

Header file (.h)
 
class NewClass {

public:

      NewClass();

      void message()const;   //A Constant member function is created

};

Source file (.cpp)

#include "NewClass.h"
#include <iostream>   // iostream header is included to use cout
using namespace std;   //namespace standard library is also included

NewClass::NewClass() {

}

void NewClass::message()const{ //message is called and accessed, which is declared in header file. It is a Constant member function

      cout<<"I have a message for you!"<<endl;   //A message will be displayed when message is called

}

Main (.cpp)

#include <iostream>
#include "NewClass.h"   // Include our classes to the main function

using namespace std;

int main(){

      const NewClass NewOb;  //New constant Object is created

      NewOb.message();  // NewOb called the constant function named message()

}


We define constant variables, functions and objects, so that corresponding data members cannot be unexpectedly modified as long as the program is running.