DEV Community

Cover image for Const in CPP
Sakshi
Sakshi

Posted on

2

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

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs