Does slicing occur in polymorphism, if you store a derived class by value, but the derived class has no extra members?
For example, if I have a class Base. But I want a custom constructor, so I implement Custom, like so:
class Base{
public:
int a;
int b;
Base(int a)
: a(a)
{ b = 2; }
};
class Custom : public Base{
public: // Note: no new members or functions!
Custom(int bb)
: Base(1)
{ b = bb; }
};
If I run it with the following code, it all works as it should. The two instances of Base is initialized correctly. They
#include <stdio.h>
int main(){
Base base = Base(1);
Base sliced = Custom(2);
Custom custom = Custom(2);
// Some printing of `a`, `b`, and sizeof(base), etc
}
It prints out the following, as you would expect:
| a | b | Size
-----------------------------
base | 1 | 2 | 8
sliced | 1 | 2 | 8
custom | 1 | 2 | 8
So, if I could ask more specifically:
- Will this always work? I.e. will I lose information of
aorb? (any members/functions ofBase) - If not, why not? Does a derived object store extra information?
- If this will always work, is it bad practice?
I have looked into using strong types, as described by this blog by FluentCpp. This will also work for my implementation, but I feel this makes the code more bloated.