Function overloading and object slicing

A case was pointed out to me where this static iterator (you can skip that article and still understand the current one) would not work as expected, without having a compile or runtime error. Things would appear to work, but from a logical point of view, they could be incorrect.

The iterator can be passed data by several structs, each struct having an overload of a function to operate on it.

struct A;
void operate(input::A& a);

struct B;
void operate(input::B& b);

For each object of these structs, the proper overload of operate is called. But the following case could not work as expected:

struct A;
void operate(input::A& a);

struct B : A;

B inherits from A and there is no operate overload for B. An expectation would be for the code to not compile because there is no function defined to operate on B. But actually, object slicing comes into play: B is a derived class and can be assigned to its base class A. And objects of type B will be operated on with A‘s operate overload. If this is the intended behavior, it’s OK.

If you want to strictly control things and make sure you have defined all the required functions, you need a way to make sure you’re given an error. Ideally a compile-time error. Continue reading Function overloading and object slicing