![]() ![]() The tutorials are designed to help you grasp various topics and concepts of C++ programming and help you excel in C++ development. If you want to learn more about such fundamental concepts of C++, you can refer to our C++ Tutorial for Beginners. With virtual functions, you can also overcome the problem of a pointer always pointing towards the base class. You can now create virtual functions of your own and use them to execute derived versions of base class functions and achieve run-time polymorphism through it. You have also seen what a pure virtual function in C++ is. In this article, you have explored virtual functions in C++ along with simple examples. Virtual void class_name() = 0 Example of Pure Virtual Functions in C++ You derive a pure virtual function in C++ using the following syntax: These types of classes cannot declare any objects of their own. It is declared in an abstract base class. It is only used as a placeholder and does not contain any function definition (do-nothing function). What is a Pure Virtual Function in C++?Ī pure virtual function in C++, also known as the do-nothing function, is a virtual function that does not perform any task. On the other hand, the print was a non-virtual function it exhibited compile-time behavior, and the output was print base class. Hence, the output shows the derived class as the pointer that was pointing to that location. ![]() Since you have declared the show function as virtual in the above code, it will be bound at runtime. Compile-Time VS Runtime Behavior of Virtual Functions in C++Ī virtual function in C++ exhibits two different types of behavior: compile-time and runtime.ĭepending on the location where the pointer is pointingĬonsider the example below to understand the behavior of virtual functions better. That’s because the pointer of the base class referred to the virtual output function of the derived class, and the non-virtual display function of the base class. To see the difference between the virtual function and a regular function, you will only declare the Output function of the base class as virtual, and keep the display function as it is.Īs you can see in the output, the output function gave the result “Output Derived class,” and the Derived function gave the result “Display Base class”. In both classes, you will create two functions: Output and Display. ![]() In the below example, you will create a base class and a derived class. Now that you know the fundamentals of the virtual function in C++, it’s time to head on to an example of using it. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |