From the course: C++ Design Patterns: Structural

Unlock the full course today

Join today to access over 24,800 courses taught by industry experts.

Implementing a hierarchical structure

Implementing a hierarchical structure - C++ Tutorial

From the course: C++ Design Patterns: Structural

Implementing a hierarchical structure

- [Instructor] Consider a company that sells different items. Each item is modeled as a separate class, book, toy, and so on. These classes expose a method that allows us to query their price, double price for book, and get price for toy. Each item can be sold individually or in a box. A box may contain multiple books, toys, or even other boxes. The box class model is a container of items. It provides an interface to add books, toys, and other boxes. These items get stored in vectors of dedicated pointers. The class also exposes a method that returns the total price of all items in the box. The total price method goes through all the items in the box and returns their sum. If the item is another box, we call its own total price method recursively until all items in the hierarchy have been visited. In the main function, I create a few items and place them in the box labeled small box. Then I instantiate another…

Contents