0

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;
}
6
  • 3
    That's not possible Commented Oct 14, 2019 at 0:43
  • 4
    This seems like the wrong approach to a problem. Commented Oct 14, 2019 at 0:43
  • 2
    Can you give a concrete example of what you're trying to accomplish? This toy example doesn't make much conceptual sense. Commented Oct 14, 2019 at 0:43
  • 2
    en.wikipedia.org/wiki/Factory_method_pattern. Essentially, just create a static method which creates an object of a correct type. Commented Oct 14, 2019 at 0:50
  • You may also check Item 1 from here: wavelino.coffeecup.com/pdf/EffectiveJava.pdf (It's Java, but you can do the same in C++). Commented Oct 14, 2019 at 0:56

1 Answer 1

1

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;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.