I have a class with const member variables. I want to put objects from that class in a vector. For adding objects to the vector, the compiler (g++ 4.0.1 on mac os x 10.4.8) requires me to provide a copy constructor and an assignment operator for that class. A copy constructor is no problem. An assigment operator is problematic, since there are const members, which can't be changed in the body of the assignment operator. So I wrote an empty assigment operator (which is a bad thing to exist), to make the compiler happy. But in the end it appears that this assignment operator is not invoked at all. Why does the compiler require such an operator, that actually can't exist because of the presence of const members, while it is not used?
Tanks in advance!
Example code:
Tanks in advance!
Example code:
Code:
/**************************************** * * Problem(?): operator= for class with const member is not desirable. But in this code the compiler says it must be there. * \****************************************/ #include<vector> #include<iostream> using namespace std; class A { private: const int unchangable; int changable; public: A(int unch, int ch); A(const A& a); A(); A& operator=(const A& a); int getUnchangable() const {return unchangable;} int getChangable() const {return changable;} }; A::A(int unch, int ch) : unchangable(unch), changable(ch) { } A::A(const A& a) : unchangable(a.getUnchangable()), changable(a.getChangable()) { } A::A() : unchangable(1), changable(2) { } A& A::operator=(const A& a) { cout << "In A::operator=" << endl; return *this; } int main() { vector<A> aas; aas.push_back(A(3, 4)); cout << aas[0].getUnchangable() << " " << aas[0].getChangable() << endl; return 0; }
Comment