Monday, July 27, 2009

How to initilize constant member variable in a class in c++?

class AB


{


const int x ;


AB()


{}


AB(int xy)


{


x = xy ;


}


~AB()


{}


};


int main()


{


AB ab(22);


return 0;


}





will it work?


If not how to initialise the const int x?

How to initilize constant member variable in a class in c++?
no it will not work...


try this...


Constructor() : x(value) { }
Reply:there is no such thing as a constant variable, its either one or the other.


if you want it to be a constant, then you just say


const int x = 4;


the way you have your code written, it wouldnt be a constant, it would be a variable, so you would just declare it as


int x;


No comments:

Post a Comment