Order of virtual function call

  c++, inheritance, oop

I don’t know if my title is correct, so fix me. But I ran into this situation.

I have 1 base class (Toy) and 2 derived class (CarToy, PuzzleToy).

class Toy
{
protected:
  double price;

public:
  Toy(double price)
  {
    this->price = price;
  }

  virtual void printType() = 0;
  friend class ToyBox;
};

class CarToy : public Toy
{
private:
  Color color;

public:
  CarToy(double price, Color color) : Toy(price)
  {
    this->color = color;
  }

  void printType()
  {
    cout << "This is a car toyn";
  }

  friend class ToyBox;
};

class PuzzleToy : public Toy
{
private:
  Size size;

public:
  PuzzleToy(double price, Size size) : Toy(price)
  {
    this->price = price;
  }

  void printType()
  {
    cout << "This is a puzzle toyn";
  }

  friend class ToyBox;
};

As you can see, there is 1 friend class named ToyBox, it’s used to addItem to the Box and print what item is in the Box so far (printBox).

class ToyBox
{
private:
  Toy *toyBox[5]; 
public:
  ToyBox() : toyBox{nullptr}, numberOfItems(0) {}

  int addItem(const CarToy &carToy)
  {
    CarToy mod = carToy;
    if (numberOfItems < 5)
    {
      toyBox[numberOfItems] = &mod;
      return ++numberOfItems;
    }
    else
      return -1;
  }

  int addItem(const PuzzleToy &puzzleToy)
  {
    PuzzleToy mod = puzzleToy;
    if (numberOfItems < 5)
    {
      toyBox[numberOfItems] = &mod;
      return ++numberOfItems;
    }
    else
      return -1;
  }

  void printBox()
  {
    for (int i = 0; i < numberOfItems; i++) {
      toyBox[i]->printType();
    }
  }
};

So I want to add a CarToy and PuzzleToy, then call printBox to verify.

int main()
{
  CarToy car(20000, red);
  PuzzleToy puzzle(30000, small);

  ToyBox box;
  box.addItem(car);
  box.addItem(puzzle);
  box.printBox();

  return 0;
}

The result is expected to be This is a car toy, This is a puzzle toy but turns out:

This is a puzzle toy

This is a puzzle toy

So I test with a simpler version and it works.

CarToy car(20000,red);
PuzzleToy puzzle(30000,small);
car.printType();
puzzle.printType();

Can anyone explain to me why this happen?

Source: Windows Questions C++

LEAVE A COMMENT