I had the following C++ code, where the argument to my constructor in the declaration had different constness than the definition of the constructor.
//testClass.hpp
class testClass {
public:
testClass(const int *x);
};
//testClass.cpp
testClass::testClass(const int * const x) {}
I was able to compile this with no warnings using g++, should this code compile or at least give some warnings? It turns out that the built-in C++ compiler on 64 bit solaris gave me a linker error, which is how I noticed that there was an issue.
What is the rule on matching arguments in this case? Is it up to compilers?
Think of it as the same difference between
Which also compiles. You can't overload based on the const-ness of a pass-by-value parameter. Imagine this case:
From the standard:
This example is covered explicitly in the overload resolution section, 13.1/3b4:
So, it is definitely OK.
Is
const int * const x
not the same likeconst int * x
becouse u already maked const?In cases like this, the const specifier is allowed to be ommitted from the declaration because it doesn't change anything for the caller.
It matters only to the context of the implementation details. So that's why it is on the definition but not the declaration.
Example:
Anyone calling f won't care that you are going to treat it as const because it is your own copy of the variable.
With int * const x, it is the same, it is your copy of the pointer. Whether you can point to something else doesn't matter to the caller.
If you ommitted the first const though in const int * const, then that would make a difference because it matters to the caller if you change the data it is pointing to.
Reference: The C++ Standard, 8.3.5 para 3: