Consider the following example, where object slicing occurs during dereference of a base pointer.
#include <stdio.h>
class Base {
public:
virtual void hello() {
printf("hello world from base\n");
}
};
class Derived : public Base{
public:
virtual void hello() {
printf("hello world from derived\n");
}
};
int main(){
Base * ptrToDerived = new Derived;
auto d = *ptrToDerived;
d.hello();
}
I want the variable d
to hold an object of type Derived
instead of an object of type Base
, without dynamic memory allocation, and without an explicit cast.
I have already looked at this question, but the solution proposed in the answer requires dynamic memory allocation, because it returns a pointer to the new object, instead of the value of the new object.
Is this possible in C++11?