How do I initialize a const data member?

The const variable specifies whether a variable is modifiable or not. The constant value assigned will be used each time the variable is referenced. The value assigned cannot be modified during program execution. Bjarne Stroustrup’s explanation sums it up briefly: A class is typically declared in a header file and a header file is typically … Read more

What is the meaning of ‘const’ at the end of a member function declaration?

When you add the const keyword to a method the this pointer will essentially become a pointer to const object, and you cannot therefore change any member data. (Unless you use mutable, more on that later). The const keyword is part of the functions signature which means that you can implement two similar methods, one … Read more

pure/const function attributes in different compilers

GCC: pure/const function attributes llvm-gcc: supports the GCC pure/const attributes Clang: seems to support it (I tried on a simple example with the GCC style attributes and it worked.) ICC: seems to adopt the GCC attributes (Sorry, only a forum post.) MSVC: Seems not to support it. (discussion) In general, it seems that almost all … Read more

Is there const in C?

There are no syntactic differences between C and C++ with regard to const keyword, besides a rather obscure one: in C (since C99) you can declare function parameters as void foo(int a[const]); which is equivalent to void foo(int *const a); declaration. C++ does not support such syntax. Semantic differences exist as well. As @Ben Voigt … Read more

Why must const members be initialized in the constructor initializer rather than in its body?

In C++, an object is considered fully initialised when execution enters the body of the constructor. You said: “i wanted to know why const must be intialized in constructor initializer list rather than in it’s body ?.” What you are missing is that initialisation happens in the initialisation list, and assignment happens in the body … Read more

How is this const being used?

const char *str in a parameter declaration indicates that the function will not try to modify the values that the str pointer points to. This means that you can call the function with a constant string. If you don’t have const in the declaration, it means that the function might modify the string, so you … Read more