Understanding C++ slicing

When you pass something to a C++ function, you have two options:

  • pass by value
  • pass by reference

pointers, by the way, are “by value”. just so you know.

So what is slicing?

when passing an object (not a primitive type) to a function by value (why would anybody do that is beyond me),  a new object is being created based on a copy of the original object. this is true for primitive as well.

Unlike primitives however, when an object is copied, it might have more then one value. so, the compiler will copy the values based on the object currently declared in the functions. confused? here is an example:


class A
{
int a;
}class B:public A
{
int b;
}
function doda(A mya)
{}

so what is the problem? the function suppose to get a copy of A. however if you instance a B and pass it, the copy constructor will only copy A:a. if you will need B:b somewhere (in another function) you can’t get it.