1

I am trying to get a new derived class pointer (with new memory location) from a parent class pointer that points to a derived class.

#include <iostream>
#include <random>
class parent{
public:
    virtual void print(){
        printf("p\n");
    }
};

class dev1: public parent{
public:
    void print(){
        printf("d1\n");
    }
};

class dev2:public parent{
public:
    void print(){
        printf("d2\n");
    }
};

int main(int argc, const char * argv[]) {
    srand(time(NULL));

    parent*bob;

    if(rand()%2){
        bob = new dev1();
    }else{
        bob = new dev2();
    }
    bob->print();

    parent * bobwannabe;

    bobwannabe = new typeof(*bob);

    bobwannabe->print();

    return 0;
}

I was hoping bobwannabe would print what bob prints. bobwannabe shouldn't point to the same object as bob but should be the same class as bob.

Right now, bobwannabe becomes a new parent. Is there a way to turn it into a new bob with it's current type or is there a specific term I should be searching up? Thank you!

WEPIOD
  • 53
  • 9
  • 1
    It's not possible to do this. The type in a `new` statement is static. Meaning, it must be known at compile time. A clone function, as outlined in the answer below, is a popular solution to your problem. – Nikos C. Dec 08 '17 at 10:04
  • 1
    Did you search at all? e.g. [How to copy/create derived class instance from a pointer to a polymorphic base class?](https://stackoverflow.com/questions/5731217/how-to-copy-create-derived-class-instance-from-a-pointer-to-a-polymorphic-base-c) / [How can a derived C++ class clone itself via a base pointer?](https://stackoverflow.com/questions/3136646/how-can-a-derived-c-class-clone-itself-via-a-base-pointer) / [C++ elegantly clone derived class by calling base class](https://stackoverflow.com/questions/36189838/c-elegantly-clone-derived-class-by-calling-base-class) – underscore_d Dec 08 '17 at 10:20

1 Answers1

1

What you want is to clone the object. You need to do it yourself by adding a virtual clone method and copy constructor to the parent class:

 virtual parent * clone() const { return new parent(*this); }

And override in all derived classes like for dev1:

 virtual parent * clone() const override { return new dev1(*this); }

and use with:

 parent *bobwannabe = bob->clone();

See also 'typeid' versus 'typeof' in C++ and don't forget to delete your objects or use smart pointers.

Mihayl
  • 3,821
  • 2
  • 13
  • 32
  • 2
    Tips: you can use `new auto(*this)` to avoid typing the type by hand. But you should rather use `std::unique_ptr` instead of a raw owning pointer. In any case, the [CRTP](https://en.wikipedia.org/wiki/Curiously_recurring_template_pattern) is the perfect tool to inject this `clone` function in all of your classes. – Quentin Dec 08 '17 at 10:20