Is there a mechanism in C ++ for creating a full copy of a derived class from a base class pointer without dynamic memory allocation?

Consider the following example when a slice of an object occurs during the dereferencing 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 to dsave the type object Derivedinstead of the type object Base, without dynamically allocating memory and without explicit casting.

I already examined this question , but the solution proposed in the answer requires dynamic allocation of memory, since it returns a pointer to a new object, not the value of a new object.

Is this possible in C ++ 11?

+4
source share
2

, , d , , , . , , ptrToDerived Base Derived , Base.

, clone std::unique_ptr<Base> Base*.

+6

, , auto D.

: . , :

Base *b = some_func();
auto d = *b;

, , b, .

+3

All Articles