bellatrix

Sakshi

Posted on October 31, 2022

Const in CPP
  • Declaration of const data member
    const int x = 10;

  • once you have initialized x you can not reassign its value

  • value can not be changed

  • initialization is not same as assignment
    const int x = 20; //initialization
    x = 20; // assignment

  • example of constant value is pi = 3.14

  • we can initialize const members from both inside and outside of class

  • We can initialize const variable from outside of the class also, like passing value from main as parameter

  • Initializer list is used to define const members from outside of the class

  • How to initialize const data member outside of a class

  • for that you must use initializer list

#include <iostream>

using namespace std;

class A{
    public:
    const int a;
    // A(int b){
    //     a = b;
    // }

      A(int b) : a(b) {}; //initializer list

    void show(){
        cout<<a;
    }

// void changename(){
  //   a = 45;   
    //}
//error: assignment of read-only member ‘A::a’
};

int main()
{
    A obj(5),obj2(6);
    obj2.show();
    obj.show();

    return 0;
}

//output : 65

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
bellatrix
Sakshi

Posted on October 31, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Const in CPP
cpp Const in CPP

October 31, 2022