Reputation: 89
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
Reputation: 170123
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:
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.
...
- 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