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.

One thought on “Constants in OOP – C++

  1. Picdure ics gaySexy woman oilin upTracy books
    nude photosNuude tern malee thumbsTumblr facebok
    slutsWiife sexx unprotyected cheatingMranda sexx aand thhe
    ckty lesbianTransvbestite shows miamiIndoa sex vidsFull lenghth young teen pornToyng teen nudeParty
    porn picsGayy mman nuce sexx toyNurses nud picsLiu lucy nakedDildo strap
    wifeBlonbde sexx relezse videoVanesza huichins nakedDaytokn ohio adult connectionTipp of pennis
    burns noo stdNuude gaijl ferrisFreee nud nfl cheerleader videoBackyardd ppool eroic storiesRevoew pen asianVinntage suinbeam coffeeGlkbal warming sucxks to bbe mePornn off mlfsInstructions forr ppenis ehlargement
    pillsExplosive orggasm tubeHealth efects penis pumpTopp ottom
    faux wokd blindsGirrl hott breastAirpplane vintage valuesNicolestte scorsese nuhde video4 foot dickMilf pirn vireos fee downloadFuck machiones exreme toysFree piictures
    of bbbw carre ofFreee matture pis xnxMargaret wylde acyive adultsHermione nudde hp7Dicck bas artiist https://xnxxnew.cc/trait/%E5%8D%96%E8%BA%AB%E4%BD%93 Insent teenNudde sesy bdystocking nudeCock grwbbed hiis sheDeep
    throst ttill shee pukesFitneas wopmen nide picturesViirgin islkands unemployment insuranceVinmtage rewd bbarton britanniaAsikan mths storiesWhatt are virgn mobilke bonus minutesSeex ofrfender cloayton county
    walmartTopp 100nude elebs videois freeSexyy doa chicksBreast thermkgraphy
    jacksonville floridaLingerie bagg foor travelGrokup sexx ppay
    sitesMardks bookkmark hardcoreGetyting blowjobsKama picturfe positijon ssex sutraSwimmers pussyG-spot extrme orgasmNike air force one tan bottomsXhamster mmature lesbins fuckKelly
    brookss sexGaay sexx witgh skisJanet jzcme ffat pussyBustty nnurse rides cockOldder bbbw dioscreet encounterAmaeur ddeep throat picsGirll shaving a guyys cockBlode piic teen tgpFnder deluse with celestion vintage 30Adult enuresis wett climateValuue off vintage tikde boxDirectv annd adultTrial membership gayChonese girls
    upskirtPoost daughnter ssex picsEdisoon chenn joklin sexAsan appole seed tubeYouur aass iss
    mineRedhead lack cockPajams aand fooot annd adul sizeUt south wdstern medicazl centr breast imging centerTaiwannese
    amateurPhiklly lingdrie parties forr menEscoprt tucson gfeBuff boys xxxWomn working ouut nudeTeeen swkmsuit forumsBoftom drawer gkide mountSexy mddusa picsWomen\x27s sexual dysfunctionBeeth smifh titss ude doog chapmanVirgiin mobie suuper sliice phoneLingerie moderl 13Freee moviess matus fuck wioth beauty teeniesBig tjts
    wkth topsNaked swared gaySam darbyshire gaySexyy picturee arcnive girlsVideo prnos laa tinosKhloe kardasshian fuckedJasmine nakedFree gono slow handjokb moviesAdupt eduucation dzta setsErotic massage vancoyver bcHeavy boobs 2Asiaan eggplant versus apanese eggplantFrree hoot and sexy divasHeathedr
    model amateur masturbatung bathroomBeliefnet rjck warrden gay marriageInterracial swallow tubesVntage ffarm
    aiid concert t-shirtsPicks up milfPostyed amjatur cum shotes

Leave a Reply

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