0

I have a base class A and 2 derived classes A1 and A2. There is another class X and I created 2 objects obj_x1, obj_x2 from this class X. I want to use derived class A1 in obj_x1 and derived class A2 in obj_x2.

How can i declare this class A object in class X so that i can use corresponding derived class objects in obj_x1 and obj_x2 instances?

class A {
  public:
  virtual void print() {
      printf("I AM A\n");
  };
};

class A1 : public A {
  public:
    void print();
};

class A2 : public A {
public:
  void print();
};


void
A1::print
()
{
  printf("I AM A1\n");
}

void
A2::print
()
{
   printf("I AM A2\n");
}

class X
{
     // problem:I want A to be A1 for obj_x1 and A2 for obj_x2 instance
     A a;
   public:
     void which_a();
};

void
X::which_a() {
  a.print();
}

int main() {
    X obj_x1;
    X obj_x2;
    obj_x1.which_a();  // I want member a in obj_X1 to be class A1
    obj_x2.which_a();  // I want member a in obj_X2 to be class A2
}
user9788
  • 11
  • 2
  • 4

1 Answers1

0

Having read through your problem a few times I think what you need is polymorphism:

class X
{
public:
  void set (std::unique_ptr<A> a) { _a = std::move(a); }
private:
  std::unique_ptr<A> _a = nullptr;
};

Then you can set _a to be an instance of A1 or A2 by passing in a pointer (unique pointer in my example) to A. If that's not what you're after then you probably need to share more details about your specific problem.

Response to edit: thanks for the update to your question. The reason why your sample code won't work is that the data member is a plain object - you will always have an instance of A and there's no way to change that. To drive this point home, if you were to make A abstract by adding a pure virtual method, you would get a compiler error along the lines of cannot instantiate abstract class. Meaning I'm trying to create an instance of A, but cannot.

Storing as a pointer is the answer here. You could use raw pointers if you want, but I would recommend a smart pointer as per my example. Storing a pointer to A means that it can be a derived instance of A. Calling a->print() as in your example will then have the desired effect.

It's probably worth reading up on polymorphism if this is new to you. Also this SO post explains why you need to use pointers/references to exploit polymorphism.

castro
  • 409
  • 3
  • 13