>
>
>
V1054. Object slicing. Derived class ob…


V1054. Object slicing. Derived class object was copied to the base class object.

The analyzer has detected a potential object slicing problem, where a derived class object is copied to a base class object.

If both the base and derived classes are polymorphic (i.e. contain virtual functions), such copying will result in losing information about the virtual functions overridden in the derived class. This may break the polymorphic behavior.

Another problem is that the object of the base class will lose information about the derived class's fields if the copy constructor was generated by the compiler in an implicit way (even if defined by the user).

Consider the following example:

struct Base
{
  int m_i;
  Base(int i) : m_i { i } { }
  virtual int getN() { return m_i; }
};

struct Derived : public Base
{
  int m_j; 
  Derived(int i, int j) : Base { m_i }, m_j { j } { }
  virtual int getN() { return m_j; }
};

void foo(Base obj) { std::cout << obj.getN() << "\n"; }

void bar()
{
  Derived d { 1, 2 };
  foo(d);
}

When passing the 'd' variable to 'foo', it will be copied to the base class object, and the 'getN' function will be called from the 'Base' class.

To avoid the slicing problem, use pointers/references:

void foo(Base &obj) { std::cout << obj.getN() << "\n"; }

No copying will take place in this case, and 'getN' will be called from the 'Derived' class.

If you still want slicing, it is recommended that you define an explicit operation for that purpose to make it clear to anyone who will be reading your code in the future:

struct Base
{
  ....
};

struct Derived : public Base
{
  ....
  Base copy_base();
  ....
};

void foo(Base obj);

void bar()
{
  Derived d { .... };
  foo(d.copy_base());
}

The analyzer does not generate the warning if there are no virtual functions in the class hierarchy and all the non-static fields are located in the base class:

struct Base
{
  int m_i;
  int m_j;
  Base(int i, int j) : m_i { i }, m_j { j } { }
  int getI() { return m_i; }
  int getJ() { return m_j; }
};

struct Derived : public Base
{
  Derived(int i, int j) : Base(i, j) { }
  virtual int getN() { return m_j; }
};

This diagnostic is classified as:

  • CERT-OOP51-CPP