What is the difference between a static and const variable?

前端 未结 17 1789
天命终不由人
天命终不由人 2020-11-29 18:39

Can someone explain the difference between a static and const variable?

17条回答
  •  悲&欢浪女
    2020-11-29 18:47

    static

    is used for making the variable a class variable. You need not define a static variable while declaring.

    Example:

    #include 
    
    class dummy
    {
            public:
                    static int dum;
    };
    
    
    int dummy::dum = 0; //This is important for static variable, otherwise you'd get a linking error
    
    int main()
    {
            dummy d;
            d.dum = 1;
    
            std::cout<<"Printing dum from object: "<

    This would print: Printing dum from object: 1 Printing dum from class: 1

    The variable dum is a class variable. Trying to access it via an object just informs the compiler that it is a variable of which class. Consider a scenario where you could use a variable to count the number of objects created. static would come in handy there.

    const

    is used to make it a read-only variable. You need to define and declare the const variable at once.

    In the same program mentioned above, let's make the dum a const as well:

    class dummy
    {
            public:
                    static const int dum; // This would give an error. You need to define it as well
                    static const int dum = 1; //this is correct
                    const int dum = 1; //Correct. Just not making it a class variable
    
    };
    

    Suppose in the main, I am doing this:

    int main()
    {
            dummy d;
            d.dum = 1; //Illegal!
    
            std::cout<<"Printing dum from object: "<

    Though static has been manageable to understand, const is messed up in c++. The following resource helps in understanding it better: http://duramecho.com/ComputerInformation/WhyHowCppConst.html

提交回复
热议问题