Reputation: 137
I want to create a class object, which will use a different class constructor depending on the given parameter. This is what I've tried so far.
class A{
public:
A(int x){
if (x == 1){
B(); //Initialize object with B constructor
else {
C(); //Initialize object with C constructor
}
}
};
class B : public A{
public:
B(){
//initialize
}
};
class C : public A{
public:
C(){
//initialize
}
};
int main(){
A obj(1); //Initialized with B constructor
return 0;
}
Upvotes: 0
Views: 165
Reputation: 9672
In a word, you can't do this in C++. The typical solution is to look towards the factory pattern.
class A {
public:
virtual ~A() {}
A() = default;
};
class B : A {
public:
B() = default;
};
class C : A {
public:
C() = default;
};
enum class Type
{
A,
B,
C
};
class Factory
{
public:
A* operator (Type type) const
{
switch(type)
{
case Type::A: return new A;
case Type::B: return new B;
case Type::C: return new C;
default: break;
}
return nullptr;
}
};
int main()
{
Factory factory;
A* obj = factory(Type::B); //< create a B object
// must delete again! (or use std::unique_ptr)
delete obj;
return 0;
}
Upvotes: 1