Question

I saw that many people use new to create instances of the derived classes and then they keep a pointer to base in some container. Does that have any advantage with respect to using a container for each derived class? With this I meant something like the following

class A
  {
 public:
  vector<Base*> bases;
  set<Derived1> der1;
  set<Derived2> der2;
  //other stuff
  };

Edit: removed the second part of the question and added as a comment.

Was it helpful?

Solution

If you do the following

vector<base*> bases;

You can then use polymorphism on your objects. Imagine that you have a base class named Vehicule. It has a move() method to go from point A to point B.

class Vehicule
{
  public:
    virtual void move(){}
}

Then you have two derived classes : Car and Submarine

class Car : public Vehicule
{
  public:
    void move()
    {
       checktires(); 
       drive();
    }
}

And your Sub class

class Submarine : public Vehicule
{
  public:
    void move()
    {
       submersion(); 
       propulsion();
    }
}

Because the move method is a virtual one, you'll be performing polymorphism. Which is a mechanism that allows you to call the same function but have different behaviours based on the dynamic type of your objects.

I'll try to explain that sentence the best I can. Now that you have the Vehicule, Car and Submarine classes, you will create an array (or a stl containers like a vector) of Vehicule pointers.

std::vector<Vehicule*> objects; 
objects.push_back(new Car());
objects.push_back(new Submarine());
objects[0]->move();
objects[1]->move();

The first call to move will call the move method defined in the Car method. And the second one will call the move defined in Submarine. Because you may have a vector of Vehicule* but when you call the function and because it is virtual, you are calling the appropriate version of it. And by calling only one function you have different behaviours. You may add as many derived class of Vehicule, you just have to adapt the move method.

You should search stackoverflow for polymorphism, there are far more detailed and accurate answers that the one I just wrote.

Sorry for the mistakes, I'm not a native-english speaker.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top