Problem summary
I don't know how to create an object of a derived class with the new-operator through a function (not a constructor), and have a base class pointer point to it.
Setup
I have an abstract base class and a derived class in my project:
class Base
{
// stuff
};
class Derived : public Base
{
//stuff
//constructor:
Derived(args);
};
I also have function that returns a Derived object.
Derived func(args);
At some point, I declare a base class pointer
Base* ptr = { nullptr };
and I want it to point to a Derived object later-on.
What I want
I want to create a Derived object using func, and be able to access it through the pointer ptr later in the code.
What I did so far
I know that it works to use the derived class's constructor
ptr = new Derived(args);
or simply its default constructor, if it exists
ptr = new Derived;
However, I have good reasons why I cannot use the constructor in my case, since the configuration of the derived object is more complicated. In this case I want to create this object with the function func.
I know that this,
ptr = new func(args);
does not work, since new expects a type. How can I achieve a behavior like this?
Thanks in advance for any advice and helpful replies.
Note: I'm using new since I need to access the Derived object also outside the scope of its creation.
funcsuch that it returnsDerived*instead ofDerived? If so, don't forget to make destructor ofBasevirtual. You can also writeDerived d = func(args); ptr = &Derived;, just it's kind-of fragile, sincedmust then outlive any dereferencing ofptr.dwill not outlive the pointer, which is why I usednewso far.funcmight be the best option, but if you cannot modifyfuncthenptr = new Derived(func(args))might work.