I have a class with const members and one constructor that calls another constructor with added values. Usually I could use a colon initializer for this, but the function is complex ( printf / sprintf - for example) and requires me to use the variable on the stack, so I have to do this in the constructor body and use assign *this to the new object. But of course this is not true because my member variables are const .
class A { public: A(int b) : b(b), c(0), d(0) // required because const { int newC = 0; int newD = 0; myfunc(b, &newC, &newD); *this = A(b, newC, newD); // invalid because members are const // "cannot define the implicit default assignment operator for 'A', because non-static const member 'b' can't use default assignment operator" // or, sometimes, // "error: overload resolution selected implicitly-deleted copy assignment operator" }; A(int b, int c, int d) : b(b), c(c), d(d) { }; const int b; const int c; const int d; }; A a(0);
(I did not explicitly delete the assignment operator.) I declared const members because I would like them to be publicly available, but not mutable.
Is there any canonical way to solve this problem without using scary throws and forcibly redefining const ness members? What is the best solution here?
source share