Stepan Loginov
Stepan Loginov

Reputation: 1767

I need assignment operator back

I have a lot of classes that inherit from some Base.

At some point const member (not static) was added to Base class. To initialize it I added constructor to Base and children.

But (As far as I understand) this action removed default assignment operator. I need this operator back. Now I need to add custom assignment operator to each class that inherit from "Base". There are a lot of classes. What is simplest way to solve such situation?

UPD: Simple example

class SerializationBase : {
    const SerializationType type;
    ... 
    public:
    SerializationType GetType() {return type;}
}

class SomeObject : public SerializationBase {
   ... // a lot of different fields
   public:
   SomeObject() : SerializationBase(SerializationType::SomeType);
}

class SomeAnotherObject : public SerializationBase {
   ... // a lot of different fields
   public:
   SomeAnotherObject() : SerializationBase(SerializationType::SomeAnotherType);
}

The code that didn't work after adding const SerializationType :

SomeObject some = Deserialize<SomeObject>(serializedData);

where Deserialize is:

template <typename T>
T Deserialize(SerializedData);

what I want: Simplest way to make it work. (maybe some class context independent realization of assignment operator that I can copy-paste in each class or so)

Upvotes: 0

Views: 83

Answers (1)

Sorin
Sorin

Reputation: 11968

The problem is that to implement the default assignment operator you need to deal with the const member.

There are 3 options for you:

  1. Implement your own assignment operator in the base class. You'll have to figure out what to do about that member since you won't be able to change it's value. All the other classes will rely on your custom assignment operator automatically and should generate the default assignment operator for them.
  2. Remove the const from the member. Now the default assignment should work just fine and be automatically inherited by all the other classes.
  3. Split your class into an assignable base and non-assignable base. The non-assignable base would only have the const member and inherit from the assignable one. You now need to go around and the change the classes to inherit from the proper base version.

I would go for the first option, but I don't know the specifics around that const member.

Upvotes: 4

Related Questions