can i destroy base class and recreate it in derived with this trick?
class base: noncopyable
{
base(); //ctor with none param
base(int x); //ctor with one param
base(int x, int y); //ctor with two param
virtual ~base();
}
struct params
{
int x;
int y;
enum
{
typeNoneParam, //neither x nor y is defined
typeOneParam, //only x is defined
typeTwoParam //x and y both are defined
}typeParam;
}
class Derived
{
Derived(params p); //construct base class conditionally by p.typeParam
}
Derived::Derived(params p)
:base() //default typeNoneParam
{
//typeNoneParam need not do special process
if (p.typeParam == params::typeOneParam)
{
base::~base(); //delete the default-typeNoneParam creation by base-dtor
base(p.x); //recreate the new base with one-param base-ctor
}
if (p.typeParam == params::typeOneParam)
{
base::~base(); //delete the default-typeNoneParam creation by base-dtor
base(p.x, p.y); //recreate the new base with two-param base-ctor
}
}
All declaration for class derived and base cannnot change, struct params cannnot either.
Only Implementation of derived class is changing-permitted.
can anyone give idea about is that implematation right? And any other more gentle implementation satisfy this scenario(init noncopyable base class with dynamically-choosing base-ctor) well?
The Derived class constructor depends on a valid Base class object being constructed first. By destroying the Base class I’m almost positive you’re flirting with Undefined Behavior. You might see this manifested with virtual functions for example.
The proper way to do this is for the Derived class to pass the parameters into the Base class constructor as part of the initialization list: