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?
- What is the meaning of each of the declarations
- Why does all 3 declarations conflict with object functions but only 2 with pointer functions?
- Please elaborate that conflict is between
l12andl13, even thoughl12does not containconstkeyword - Really sorry if trivial question
The “problem” is that
constness of a parameter’s value doesn’t participate in overloading!First,
Bar constandconst Barare already identical meaning, so they would automatically have a problem. But as a function parameter theconstdoesn’t apply to overloading so theBarversion of the function also looks the same too. Theconstin the paremeter only tells the compiler that you don’t intend to modify it in the function body.For the same reason,
Bar*andBar* constare treated the same: Theconstapplies 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 aconstobject (of typeBar). Since the type is different it does participate in overloading and allows that function to be unique.