Question

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.

Was it helpful?

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.

OTHER TIPS

This is out of your reach: user-defined operators must take at least one parameter of a user-defined (not built-in) type. Since pointers are built-in types, you are out of luck here. f = b will be legal no matter what you do.

No slicing will occur in your example:

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

f = b;

You're assigning the pointer, not the value. The f pointer and the b pointer are the same size (the size of a pointer on the architecture you're running on), so they will always fit into each other with no slicing. The objects themselves aren't affected by this assignment and are not sliced.

But this would cause the 'new Foo()' to leak. After the assignment, both f and b will point to the 'new Bar()' and you'll have no pointer left to the 'new Foo()' which you would be able to delete it with.

Can I suggest you use std::unique_ptr instead of raw pointers. This will take care of deleting for you.

std::unique_ptr<Foo> newInstance()
{
    return new Foo();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top