Search code examples
c++inheritanceassignment-operatorprivate-methodsobject-slicing

Allow operator= being used only between objects of the same class?


I have a class hierarchy and I want to forbid doing this:

Foo *f = new Foo();
Bar *b = new Bar();

f = b;

where Foo is a superclass of Bar. Doing this would slice the Bar part of the object. I know you can solve this by making operator= private, but is it possible to only forbid the assignment operator from being used if they are of different types?

Like making operator= private but still allowing this:

Bar *b1 = new Bar();
Bar *b2 = new Bar();

b1 = b2;

Assume subclasses will be made to Bar as well.


Solution

  • Since you are talking about slicing, I assume what you are actually trying to prevent is this:

    Foo f;
    Bar b;
    
    f = b;
    

    In this case, yes, you can prevent the assignment by making the appropriate operator= private.

    You cannot prevent pointer assignments, but note that a pointer assignment would not result in slicing anyways.