May 13, 2011

C++ Error: Assignment of data member in read only structure

 

What the compiler actually said:

assignment of data-member 'Namespace::ClassName::StructMember' in read-only structure 

This can be confusing because "StructMember" is in a struct. But that structure isn't read-only, or at least when you look at the member variable it belongs to, it doesn't appear to be.  

What the compiler should have said:

assignment of data-member 'Namespace::ClassName::StructMember' in a member function that has been marked 'const'. Remove the 'const' method qualifier

If you don't try and write const correct code you might never see this error. Many programmers (especially experienced C programmers) have never written:

void SomeFunction() const;

and when they first see that trailing const they have no idea what it means.  It's a promise to the compiler that this method doesn't modify the state of the class object. It's easy to forget during maintenance and modification that you need to remove this in the .h and .cpp file when you change the method such that it does modify the state of the object.

See the rest of the Series on C++ Compiler Errors

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.