Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

A Beginners Guide: Polymorphism, Virtual Functions, and Abstract Classes With C++

Posted on Aug 9 Polymorphism comes from two words: Poly which means many and Morph which means form. Polymorphism as a word simply means many forms. In Objected Oriented Programming, Polymorphism refers to a Function or an object behaving in different forms. Using a woman as an example, she could be a wife to one person, a mother to another, a friend to another, and a relative to another. The same woman, yet her job varies from person to person.This is the idea polymorphism seeks to replicate in Objected Oriented Programming. Polymorphism gives us the ability to use the same expression to denote different operations.Types of Polymorphism include run-time polymorphism and compile time polymorphism. Compile time polymorphism is achieved through function overloading or operator overloading, while run-time polymorphism is achieved through virtual functions. By using function overloading, we can have two functions that share the same name but carry out different operations. Below is an illustration:In the above code snippet, the Shape class has two area functions. The area function computes the area of a shape and returns its result. The first area function receives one argument, while the second takes two. The same function, but when given two arguments, it does something different from when given one. Isn't that incredible😁?Given, we have the class PetType. This class defines a constructor that initializes the name member variable under the private access specifier. This class also declares the print function that prints out the name member variable. The implementation of this class is given below.Using the above codes as base class, we can derive the dogType class from our base class. This class also has a constructor which initializes breed and the name member variables of this derived class.Note that the name variable of our base class is under the private member access specifier, and this implies that the derived class does not have a direct to this variable. In order to have access to this variable we have to do that through the public functions that were defined above, this is because our derived class has direct access to these functions.In the print function of our derived class, since we don't have direct access to the name variable then we can't directly print out the name variable print function, so to print out the name variable we have to call the print() of our base class.We don't have access to the name variable in the constructor of our derived class too, and hence the reason behind the code above. Remember, the code above is the same as the code below but in a simplified form, I think 🤔.**Note: **We can solve the problem of not having direct access to the name variable of our base class in the derived class by changing the private specifier to protected.With the above modification: We are at complete liberty to make the modifications below without encountering an error during runtime of our program.Given that, we have the function below that takes in an object of the class PetType as an argument and then calls the print method(function) of the object.In our main functionThe result of running our program:Now you may think the output of line 7 and line 11 of the codes in the main function may run to give us the same output. From the output of running the program you realize line 7 prints out Tommy on one line and German Shepherd on another line but line 11 prints out just Tommy.To explain why this happens: remember, our derived class has 2 print() functions; the one it inherits from the base class and the other that print() that is written in the derived class. Remember in the definition of the callPrint function the parameter type that was assigned to p was of the class PetType and as such the compiler calls the PetType::print() on line 11.This is a possible bug that we seek to resolve in C++ in the sense that we want line 11 to have the same output as line 7 and this because the print function related to the dogType class should print out both the breed and the name variables. In the definition of the print function in the base class, we could prefix that the declaration with the virtual keyword. By marking a function as "virtual," you indicate to the compiler that the function should be dynamically bound at runtime, which means the correct implementation of the function will be determined based on the actual object type.With this slight modification in the base class, our output becomesVirtual functions are important because they enable you to write more flexible and extensible code. They allow you to design base classes with certain behaviors while leaving the specific implementation details to derived classes. This promotes code reusability and modularity, as well as simplifies the management of objects with varying behaviors.When a function is prefixed with the virtual keyword, the compiler is instructed to decide the function's behavior based on the object type of the function rather than just the pointer or reference pointing to the function.Assume we have a shape class with a draw function that draws the shape. This function's implementation is shown below.The shape class serves as the base class for other derived classes such as Rectangle and Oval among others.Because the definitions of the draw function is more specific to a particular shape, each derived class can provide an appropriate definition of these functions.The definition of the base class which is the Shape class requires that we write the definition of the draw function in the base class, but at this point which is in the base class there is no shape to draw. As a result, the draw function of our base class must have no code. How do we resolve this?You may have guessed it right, that is, we define the virtual class as stated below:There is a disadvantage to defining the function like stated above. In the code above, since we have provided a definition to the draw function of the Shape class, we give users of the class the liberty to create objects of the Shape class and call the draw function on the object when the draw function does nothing. In order to prevent this, C++ gives us abstract classes or Pure Virtual Functions. To make a function a pure virtual function, we declare it as a virtual function and then use the assignment operator to assign the function's declaration to 0.Since this function has no definition but it just an abstract class, C++ does not allow objects of this class to be created, but we can create a pointer from the base class that will point to the derived class.Polymorphism is an important concept of object-oriented programming. It simply means more than one form. That is, the same entity (function or operator) behaves differently in different scenarios.To make a function virtual, we prefix the function declaration in our base class with the virtual keyword.Hey guys😊 Elvis here, Don't forget to ask all your questions in the comment section right below. Like and share this please🥲. Happy Coding out thereTemplates let you quickly answer FAQs or store snippets for re-use. Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink. Hide child comments as well Confirm For further actions, you may consider blocking this person and/or reporting abuse Nayan Pahuja - Jul 26 Max Lockwood - Jul 26 Gopi Gorantala - Jul 25 IagoLast - Jul 26 Once suspended, gyauelvis will not be able to comment or publish posts until their suspension is removed. Once unsuspended, gyauelvis will be able to comment and publish posts again. Once unpublished, all posts by gyauelvis will become hidden and only accessible to themselves. If gyauelvis is not suspended, they can still re-publish their posts from their dashboard. Note: Once unpublished, this post will become invisible to the public and only accessible to Gyau Boahen Elvis. They can still re-publish the post if they are not suspended. Thanks for keeping DEV Community safe. Here is what you can do to flag gyauelvis: gyauelvis consistently posts content that violates DEV Community's code of conduct because it is harassing, offensive or spammy. Unflagging gyauelvis will restore default visibility to their posts. DEV Community — A constructive and inclusive social network for software developers. With you every step of your journey. Built on Forem — the open source software that powers DEV and other inclusive communities.Made with love and Ruby on Rails. DEV Community © 2016 - 2023. We're a place where coders share, stay up-to-date and grow their careers.



This post first appeared on VedVyas Articles, please read the originial post: here

Share the post

A Beginners Guide: Polymorphism, Virtual Functions, and Abstract Classes With C++

×

Subscribe to Vedvyas Articles

Get updates delivered right to your inbox!

Thank you for your subscription

×