I'm using gcc version 4.5.0. Using the following simple example I would assume to get an error invalid conversion from double* to const double*
#include <iostream>
using namespace std;
void foo(const double *a)
{
cout<<a[0]*2.<<endl;
}
int main()
{
double *a=new double[2];
a[0]=1.;
a[1]=2.;
foo(a);
return 1;
}
Why is it compiling without errors?
A counterexample is the following one which is similar:
#include<iostream>
using namespace std;
void foo(const double **a)
{
cout<<a[0][0]*2.<<endl;
}
int main()
{
double **a=new double*[2];
a[0]=new double[2];
a[1]=new double[2];
a[0][0]=1.;
foo(a);
cout<<a[0][0]<<endl;
return 1;
}
(Solution for the second example: define foo as foo(const double*const* a). Thanks to Jack Edmonds comment this explains the error message)
Generally, you are allowed to implicitly make things "more constant" but not "less constant" in C and C++. Therefore, you are allowed to pass a non-const object to a function that takes a const object.
Basically the const parameter in the method declaration is the function's way of promising not to modify the parameter.
You can see this question for more information: Question about const_cast in c++
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