Reusable member function in C++

Viewed 128

I'm using this member function to get pointer to object:

    virtual Object* Create()
    {
        return new Object();
    }

It's virtual so I can get pointer to derived objects, now I'm doing it like this:

    virtual Object* Create()
    {
        return new Foo();
    }

It is working correctly, but I'd like to do something like this to prevent any mistakes and also to make it easier so I don't have to rewrite that function every time I make new class:

    virtual Object* Create()
    {
        return new this();
    }

I was trying to find how to do this but couldn't find anything useful, maybe it's not possible. I'm using MSVC compiler with C++17

1 Answers

You can get the type from this pointer as

virtual Object* Create() override
{
    return new std::remove_pointer_t<decltype(this)>;
}

LIVE

PS: Note that you still need to override the member function in every derived class. Depending on your demand, with CRTP you can just implement Create in the base class. E.g.

template <typename Derived>
struct Object {
    Object* Create()
    {
        return new Derived;
    }
    virtual ~Object() {}
};

then

struct Foo : Object<Foo> {};
struct Bar : Object<Bar> {};

LIVE

Related