Vishvajeet T
Vishvajeet T

Reputation: 89

Object slicing while casting in C++

How casting statically while down casting, leads to object slicing? Like in the case below;

class Parent{ // base class
public:
    virtual void draw();
};

class Child: public Parent{ //derived class
public:
    void draw()
    {
       static_cast<Parent>(*this).draw();
       // do other stuff
    }
};

Upvotes: 1

Views: 1362

Answers (1)

Your'e not down-casting, your'e up-casting (sort of).

And it causes slicing because static_cast<Parent>(*this) creates a new temporary Parent object by copying *this. It's essentially equivalent to the following:

Parent{*this}.draw();

As per the C++ standard:

[expr.static.cast/1]

The result of the expression static_­cast(v) is the result of converting the expression v to type T. If T is an lvalue reference type or an rvalue reference to function type, the result is an lvalue; if T is an rvalue reference to object type, the result is an xvalue; otherwise, the result is a prvalue. The static_­cast operator shall not cast away constness.

[basic.lval/1.2]

...

  • A prvalue is an expression whose evaluation initializes an object or a bit-field, or computes the value of the operand of an operator, as specified by the context in which it appears.

...

Upvotes: 2

Related Questions