Possible Duplicate:
Difference between const declarations in C++
#include <iostream>
class Bar{};
void foo(const Bar x){} //l5
void foo(Bar x){} //l6
void foo(Bar const x){} //l7
////pointer functions
void foo(const Bar* x){} //l11
void foo(Bar* x){} //l12
void foo(Bar* const x){} //l13
Compiler output: (long story short l5
,l6
,l7
conflict; but only l12
,l13
conflict)
untitled.cpp:6:6: error: redefinition of ‘void foo(Bar)’
untitled.cpp:5:6: error: ‘void foo(Bar)’ previously defined here
untitled.cpp:7:6: error: redefinition of ‘void foo(Bar)’
untitled.cpp:5:6: error: ‘void foo(Bar)’ previously defined here
untitled.cpp:13:6: error: redefinition of ‘void foo(Bar*)’
untitled.cpp:12:6: error: ‘void foo(Bar*)’ previously defined here
What going on?
l12
and l13
, even though l12
does not contain const
keywordA function becomes const when the const keyword is used in the function's declaration. The idea of const functions is not to allow them to modify the object on which they are called. It is recommended the practice to make as many functions const as possible so that accidental changes to objects are avoided.
const after member function indicates that data is a constant member function and in this member function no data members are modified.
const member functions Declaring a member function with the const keyword specifies that the function is a "read-only" function that doesn't modify the object for which it's called. A constant member function can't modify any non-static data members or call any member functions that aren't constant.
A "const function", denoted with the keyword const after a function declaration, makes it a compiler error for this class function to change a member variable of the class. However, reading of a class variables is okay inside of the function, but writing inside of this function will generate a compiler error.
The "problem" is that const
ness of a parameter's value doesn't participate in overloading!
First, Bar const
and const Bar
are already identical meaning, so they would automatically have a problem. But as a function parameter the const
doesn't apply to overloading so the Bar
version of the function also looks the same too. The const
in the paremeter only tells the compiler that you don't intend to modify it in the function body.
For the same reason, Bar*
and Bar* const
are treated the same: The const
applies to the value of the parameter (not what's pointed to) and does not participate in overloading, so you've defined the same function.
On the other hand const Bar*
means something totally different: A non-const pointer to a const
object (of type Bar
). Since the type is different it does participate in overloading and allows that function to be unique.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With