Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are const class members useful when the assignment operator is overloaded?

Tags:

c++

I have a class with a member which is not changed by the methods of the class, so I marked it as const. My problem is that I was using the default assignment operator just like a copy constructor in order to avoid multiple declarations. But in this case the assignment operator is not automatically generated, so I get some compiler errors: 'operator =' function is unavailable. This seems like that there is no real life scenario where const class members can be actually used (e.g. have you seen any const member in the STL code?).

Is there any way to fix this, beside removing the const?

EDIT: some code

class A
{
public :
   const int size;
   A(const char* str) : size(strlen(str)) {}
   A() : size(0) {}
};


A create(const char* param)
{
    return A(param);
}


void myMethod()
{
    A a;

    a = create("abcdef");
    // do something

    a = create("xyz");
    // do something
}
like image 938
Andrei Bozantan Avatar asked Jan 16 '12 07:01

Andrei Bozantan


2 Answers

Here's your misconception which is causing this issue:

[..] which is not changed by the methods of the class

The member variable is changed by a method of your class, the assignment operator. Including the one synthesized by the compiler. If you mark a member variable as const, this expresses that this variable will (should not!) change its value during the lifetime of the object. So clearly, assigning a new value to the object violates this statement. So if you indeed don't want the member to change, just don't make it const.

like image 92
Frerich Raabe Avatar answered Sep 28 '22 02:09

Frerich Raabe


const members are ideal in many, many cases. of course, there is the obvious case where a value should not or must not change, but it's also an important restriction for optimization and concurrency -- not every type needs or should have an assignment operator.

if the member needs the behavior of assignment, then the variable must not be const.

when the value/member must not mutate or be mutated by this, it's clearer to provide a separate interface for the variable members (or even a subtype->composition in more complex cases):

class t_text {
public:
// ...
public:
    void setString(const std::string& p);
private:
    const t_text_attributes d_attributes;
    std::string d_string;
};

therefore, my suggestion is to hide the assignment operator, and to make the 'mutable chunk' or member set-able for clarity:

text.setString("TEXT"); // << Good: What you read is what happens.
text = otherText; // << Bad: Surprise - attributes don't actually change!
like image 22
justin Avatar answered Sep 28 '22 00:09

justin