I have a class with a constructor which takes a non-const reference which is assigned to a member of the class. Now I want to create a const object of said class, but the constructor complains if I pass a const reference to the constructor. The code below which is a simplification of my original code demonstrates the problem.
As far as i can tell, there should be no problems with creating a const object since it is based on const data?
How can achieve what I'm trying to do in create_const_a
?
#include <iostream>
class A {
private:
double &d;
const int &i;
public:
A(double &dd, const int &ii)
: d(dd), i(ii)
{}
void set_d(double a) {
d = a;
}
void print() const {
std::cout << d << " " << i << std::endl;
}
};
A create_a(double &dd, const int &ii) {
return A(dd,ii);
}
const A create_const_a(const double &dd, const int &ii) {
return A(dd,ii);
}
void foo(A a)
{
a.set_d(1.3);
a.print();
}
void bar(const A a)
{
a.print();
}
int main(int argc, char *argv[])
{
double d = 5.1;
int i = 13;
foo(create_a(d,i));
bar(create_const_a(d,i));
return 0;
}
The error I get is:
test.cc: In function ‘const A create_const_a(const double&, const int&)’:
test.cc:27:17: error: binding ‘const double’ to reference of type ‘double&’ discards qualifiers
return A(dd,ii);
^
test.cc:8:3: note: initializing argument 1 of ‘A::A(double&, const int&)’
A(double &dd, const int &ii)
^
Update: After learning some new things about how const works with objects and non-const references within them, I eventually solved the original problem by introducing another type, say ConstA
which only contains const references, which could then be used in each of the problematic cases.