From the course: Object-Oriented Programming with C++

Unlock this course with a free trial

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

Virtual functions: The basics

Virtual functions: The basics - C++ Tutorial

From the course: Object-Oriented Programming with C++

Virtual functions: The basics

- [Instructor] Now that we've discussed what polymorphism is, let's apply it to our review system. The goal is to make the following code work. In the main function, we'll construct a vector of review pointers, which we'll then fill with pointers to ProductReview and RestaurantReview instances. Although the pointers are different, we can pass the vector as an argument to the calculateAverageRating function. Thanks to polymorphism, the function will calculate ratings across different types of reviews. Okay, let me walk you through the changes we need to make to enable this. First in our base review class, we must add the virtual keyword to methods that derived classes will override. So I make displayDetails and getRating virtual. The virtual keyword tells C++ that when we call this method through a pointer or reference the review, it should look for overridden versions in derived classes. Next, in our derived classes, we'll use the override keyword to make our intentions clear. Let's…

Contents