
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?
Contents
Constants are essential because they represent fixed values and prevent accidental modifications.
- Data Safety: Ensures values do not change mistakenly during program execution.
- Readability: Makes the code clearer by indicating that a value is fixed.
- Maintainability: If a constant changes in the future (e.g., tax rate), we only update it in one place.
- 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.
- 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
- 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
- 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
Aspect | Normal Variable | Constant Variable | Static Variable |
---|---|---|---|
Value | Can change anytime | Fixed, cannot be modified | Shared among all objects |
Initialization | Can be later | Must be at declaration/constructor | Declared once, defined outside class |
Usage | For dynamic values | For fixed values | For shared/persistent values |
Safety | Risk of accidental changes | Protected against changes | Prevents duplication, ensures persistence |
Constants ensure stability and prevent accidental modification.
Practice Exercises
- Write a program that uses a constant
PI
to calculate the area of a circle. - Create a class with a constant roll number that is initialized via constructor.
- Write a program to demonstrate a constant pointer to constant data.
- Make a constant member function that returns the value of a private variable.
19 thoughts on “Constants in OOP – C++”
**mind vault**
Mind Vault is a premium cognitive support formula created for adults 45+. It’s thoughtfully designed to help maintain clear thinking
**mindvault**
mindvault is a premium cognitive support formula created for adults 45+. It’s thoughtfully designed to help maintain clear thinking
**prostadine**
prostadine is a next-generation prostate support formula designed to help maintain, restore, and enhance optimal male prostate performance.
**sugarmute**
sugarmute is a science-guided nutritional supplement created to help maintain balanced blood sugar while supporting steady energy and mental clarity.
**glpro**
glpro is a natural dietary supplement designed to promote balanced blood sugar levels and curb sugar cravings.
**prodentim**
prodentim an advanced probiotic formulation designed to support exceptional oral hygiene while fortifying teeth and gums.
**vitta burn**
vitta burn is a liquid dietary supplement formulated to support healthy weight reduction by increasing metabolic rate, reducing hunger, and promoting fat loss.
**synaptigen**
synaptigen is a next-generation brain support supplement that blends natural nootropics, adaptogens
**zencortex**
zencortex contains only the natural ingredients that are effective in supporting incredible hearing naturally.
**yusleep**
yusleep is a gentle, nano-enhanced nightly blend designed to help you drift off quickly, stay asleep longer, and wake feeling clear.
**nitric boost**
nitric boost is a dietary formula crafted to enhance vitality and promote overall well-being.
**glucore**
glucore is a nutritional supplement that is given to patients daily to assist in maintaining healthy blood sugar and metabolic rates.
**wildgut**
wildgutis a precision-crafted nutritional blend designed to nurture your dog’s digestive tract.
**breathe**
breathe is a plant-powered tincture crafted to promote lung performance and enhance your breathing quality.
**energeia**
energeia is the first and only recipe that targets the root cause of stubborn belly fat and Deadly visceral fat.
**boostaro**
boostaro is a specially crafted dietary supplement for men who want to elevate their overall health and vitality.
**pinealxt**
pinealxt is a revolutionary supplement that promotes proper pineal gland function and energy levels to support healthy body function.
**prostabliss**
prostabliss is a carefully developed dietary formula aimed at nurturing prostate vitality and improving urinary comfort.
**potentstream**
potentstream is engineered to promote prostate well-being by counteracting the residue that can build up from hard-water minerals within the urinary tract.