Constants in OOP – C++

Constants in OOP – C++

In our daily life, there are some values that never change. For example:

  • The number of days in a week is always 7.
  • The speed of light in a vacuum is constant.
  • A student’s roll number assigned once in a class does not change.

These values remain fixed regardless of circumstances. Similarly, in C++, if we want to create a variable whose value should not be altered during the program execution, we declare it as constant using the const keyword. The detailed tutorial can be visited here.

A constant in C++ is a variable whose value cannot be modified after initialization.

Why Do We Need Constants?

Constants are essential because they represent fixed values and prevent accidental modifications.

  1. Data Safety: Ensures values do not change mistakenly during program execution.
  2. Readability: Makes the code clearer by indicating that a value is fixed.
  3. Maintainability: If a constant changes in the future (e.g., tax rate), we only update it in one place.
  4. Reliability: Prevents bugs that may occur due to unintended modification of important values.

Declaring Constants

In C++, constants can be declared using the const keyword.

const int daysInWeek = 7;
const float PI = 3.14159;

Once declared, their values cannot be changed.

Example 1: Basic Constant Usage

#include <iostream>
using namespace std;

int main() {
    const float PI = 3.14159;   // Constant declaration
    float radius = 5;

    float area = PI * radius * radius;
    cout << "Area of circle = " << area << endl;

    // PI = 3.14;   // ❌ Error: cannot modify a const variable

    return 0;
}

Output:

Area of circle = 78.5397

Here, PI remains fixed throughout the program.

Constants in Classes

We can also use constants inside classes. They are useful for defining values that are common for all objects but should not change, like maximum marks or fixed tax rates.

#include <iostream>
using namespace std;

class Student {
public:
    const int rollNumber;   // constant data member

    Student(int r)  {
      rollNumber = r;// Initialization using constructor
    }

    void show() {
        cout << "Roll Number: " << rollNumber << endl;
    }
};

int main() {
    Student s1(101);
    Student s2(102);

    s1.show();
    s2.show();
    return 0;
}

Output:

Roll Number: 101
Roll Number: 102

Here, rollNumber is constant—once assigned through the constructor, it cannot change.

Const Member Functions

A member function can also be declared as const.
This means it cannot modify any member variables of the class.

class Demo {
    int value;
public:
    Demo(int v) {
      value = v;
    }

    int getValue() const {   // const function
        return value;
    }
};

If you try to change value inside getValue(), the compiler will give an error.

Pointers and Constants

Constants can also be used with pointers in three different ways. To make it simple, think of a pointer as an arrow that shows the address of a variable, while const controls whether the arrow itself can move or whether the value it points to can change.

  1. Pointer to Constant Data
    Here the data is fixed, but the pointer can point somewhere else.
    Daily life example: You have a book that you can only read but not edit. However, you can put down this book and pick up another. const int x = 10; const int* ptr = &x; // data is constant, pointer can change
  2. Constant Pointer
    Here the pointer cannot move to another address, but the data at that location can still change.
    Daily life example: Imagine you are tied to a single chair. You cannot move to another chair, but you can still adjust the cushion on your chair. int y = 20; int* const ptr2 = &y; // pointer is constant, data can change
  3. Constant Pointer to Constant Data
    Here both the pointer and the data are fixed.
    Daily life example: You are tied to a chair, and the cushion on that chair is also locked—you can neither move to another chair nor adjust the cushion. const int z = 30; const int* const ptr3 = &z; // both pointer and data are constant

Daily Life Example

Think of days in a week.
No matter where you live, you always have 7 days in a week.
This is just like a constant variable: it is defined once and never changes.

Or consider a roll number in a classroom—assigned once and fixed for the student.
That’s how constants work in C++.

Comparison: Normal vs Constant vs Static Members

AspectNormal VariableConstant VariableStatic Variable
ValueCan change anytimeFixed, cannot be modifiedShared among all objects
InitializationCan be laterMust be at declaration/constructorDeclared once, defined outside class
UsageFor dynamic valuesFor fixed valuesFor shared/persistent values
SafetyRisk of accidental changesProtected against changesPrevents duplication, ensures persistence

Constants ensure stability and prevent accidental modification.

Practice Exercises

  1. Write a program that uses a constant PI to calculate the area of a circle.
  2. Create a class with a constant roll number that is initialized via constructor.
  3. Write a program to demonstrate a constant pointer to constant data.
  4. Make a constant member function that returns the value of a private variable.

Leave a Reply

Your email address will not be published. Required fields are marked *