I was using a class from a library which has a const variable (const_var). I used this class as a member in my own class (Container), but was having problems to initialize it. For instance, the code below was an attempt to set ‘const_var’ to 10, but it actually prints 0!
#include <stdio.h> class LibraryClass { const int const_var; int non_const_var; public: LibraryClass() : const_var(0) {} LibraryClass(int const_value) : const_var(const_value){ non_const_var = 1; } int get_const_var() const {return const_var;} LibraryClass& operator= (const LibraryClass& s1){ non_const_var = s1.non_const_var; return *this; } }; class Container { LibraryClass s; public: Container() { s = LibraryClass(10); printf("%d\n", s.get_const_var()); } }; int main (){ Container c; return 0; }
That’s why: LibraryClass constructor is first called with empty arguments when I declare it on my class Container. Then, when I try to initialize another object and copy it to s, like in line 29,
s = LibraryClass(10);
I’m creating a new object from ‘LibraryClass’ which indeed has ‘const_var = 10’, but when I try to copy it, it is the overloaded operator ‘=’ that is called and it doesn’t copy the value of the const variable. Thus, s still holds the first value, 0.
The workaround is to initialize the object in the same fashion LibraryClass did with the const variable, which is:
Container() : s(10) { printf("%d\n", s.get_const_var()); }
References:
[1]