C++ Polymorphism case study

C++ Polymorphism case study

Types of polymorphism

Polymorphism has 2 types in C++: Compile time and Run time; Compile time such as operator or function overloading while runtime is concerned with virtual functions.

Here we will be concerned with the Run time polymorphism.

We have 2 ways to achieve run time polymorphism in C++ which are through references or through pointers to base class. As a simple example if we have a base class called "pet" that 's having a pure virtual function called makeNoise(), inherited by 2 classes, "Cat" and "Dog" then Polymorphism is going to be illustrated like this:

No alt text provided for this image
No alt text provided for this image
No alt text provided for this image

and with a pointer static type as "Pet" we can call the correct "makeNoise()" method in runtime

No alt text provided for this image

Put (Smart) Pointers, Not Objects, in Containers

For now everything seems pretty simple. Let's take it to the next level; Say that for some reason we need another function that saves some pets that are available for adoption. First thing that will come to your mind is: "What will be the type of the container that holds these pet objects?", Actually this is a very valid question, thinking of it we can not let it be "Pet" type as the breed part of the "Cat" and the "Dog" objects will be sliced out. Now we will figure out that this case needs polymorphism and as we discussed earlier we can implement it using references and pointers to base class "Pet" in our case. But What type of pointers shall we use? Do we use normal pointers? The problem with normal pointers will be in dynamic environments, consider our program reads the pet info from a file, we don't know how many dogs and how many cats are going to be added so we will rely on the dynamic memory "Heap". By taking this decision you take the responsibility of handling this region by freeing the resources before the owner class is destructed. In this case you will have to handle the shallow copying problem. This overhead let's us with a better choice which is the usage of smart pointers to implement polymorphism and handle heap efficiently at the same time.

we will introduce 2 functions one to add the pet and another one to make pets introduce themselves in addition to a multiset of shared pointers:

No alt text provided for this image

now let's implement our driver code:

No alt text provided for this image

O/P:

No alt text provided for this image

要查看或添加评论,请登录

社区洞察

其他会员也浏览了