const keyword usage

Hi,

I would like to know different types of using const. I am confused of using const...

for eg:

class A()
{
void B() const;
void const B();
}

and

const char C;
char const C;

What are the differences and advantages of using different syntax of const?

Thanks,
kalyan
Consider non-static member functions as having implicit additional first parameter of type ClassName *, that is equivalent to the this

So the difference of these two member functions

void B() const;
void const B();


will be visible if to show this implicit parameter explicitly. The const quualiifier after the function declarator belongs to the pointer this.

void B( const A * );
void const B( A * );


So the first function returns nothing ( void ) and has a parameter of type const A * while the second function also return "qualified nothing ( const void ) and has a parameter of type A *.
It means that inside the body of the first function you can not change members of the class while inside the body of the second function you can change members of the class. The first function may be called for const objects of the class while the second function may not.

For example

1
2
3
4
5
6
const A a1;

a1.B(); // The first function void B() const is called

A a2;
a2.B(); // The second function void const B() is called because the object is not const 


As written in the C++ Standard

The cv-qualified or cv-unqualified versions of a type are distinct types; however, they shall have the same representation and alignment requirements


So even void and const void are two distince types. So for example these two functions

void f();
const void f();


are distinct functions and a compiler shall issue an error because the name f can not be overloaded by return type.

These are equivalent declarations because order of type specifiers is not important.
1
2
const char C;
char const C;


But these declarations shall have an initializer if they are not declarations of data members of some class.
Last edited on
Topic archived. No new replies allowed.