Moataz Elmasry
Moataz Elmasry

Reputation: 2519

dynamic initialization of abstract class instances

Lets say I have the following

class Parent {
  protected: 
    virtual void overrideMe() = 0;
}

class ChildA : public Parent {
  protected: 
    void overrideMe() = 0{}
}

class ChildB : public Parent {
  protected: 
    void overrideMe() = 0{}
}

class UtilClass {
  public:
  vector<Parent> planes;
  void compute() {
    Parent& p = planes[0];
  }
}

In this case I'd get in the compute() in UtilsClass an error, that "Parent" cannot be initialized.

What I'd like to do is to fill the array "planes" (with either ChildA or childB, i.e. non mixed type) in UtilClass and do some calculations.

Do I have to use pointers during initialization, or better to use to use template? I'm almost sure that template usage is not necessary as I'd like to limit the usage to only children of Parent class.

Upvotes: 1

Views: 1126

Answers (2)

mathematician1975
mathematician1975

Reputation: 21351

You cannot have

  vector<Parent> planes;

since your Parent class is abstract and cannot be instantiated. You would need to make use of something like

  vector<Parent*> planes;

instead if you wanted to have a vector of objects that are derived from Parent by creating the derived class objects with this kind of syntax

 Parent* pNewObject = new ChildB;
 planes.push_back(pNewObject)

Upvotes: 2

Luchian Grigore
Luchian Grigore

Reputation: 258568

vector<Parent> planes; doesn't make sense because a Parent can't exist. It's an abstract class. You can have a vector of pointers or, better yet, smart pointers.

Even if Parent wasn't abstract, the vector of Parent objects would suffer from object slicing and it's probably not what you want, since it would break polymorphism.

class UtilClass {
  public:
  vector<Parent*> planes;
  void compute() {
    Parent& p = *planes[0];
  }
}

Upvotes: 5

Related Questions