Virtual function vs Pure virtual function in C++Before understanding the differences between the virtual function and pure virtual function in C++, we should know about the virtual function and pure virtual function in C++. What is virtual function?Virtual function is a member function that is declared within the base class and can be redefined by the derived class. Let's understand through an example. In the above code, we have not used the virtual method. We have created a base class that contains the show() function. The two classes are also created named as 'derived1' and 'derived2' that are inheriting the properties of the base class. Both 'derived1' and 'derived2' classes have redefined the show() function. Inside the main() method, pointer variable 'b' of class base is declared. The objects of classes derived1 and derived2 are d1 and d2 respectively. Although the 'b' contains the addresses of d1 and d2, but when calling the show() method; it always calls the show() method of the base class rather than calling the functions of the derived1 and derived2 class. To overcome the above problem, we need to make the method as virtual in the base class. Here, virtual means that the method exists in appearance but not in reality. We can make the method as virtual by simply adding the virtual keyword preceeding to the function. In the above program, we need to add the virtual keyword that precedes to the show() function in the base class shown as below: Once the above changes are made, the output would be: Important points:
What is pure virtual function?A pure virtual function is a virtual function that has no definition within the class. Let's understand the concept of pure virtual function through an example. In the above pictorial representation, shape is the base class while rectangle, square and circle are the derived class. Since we are not providing any definition to the virtual function, so it will automatically be converted into a pure virtual function. Characteristics of a pure virtual function
Syntax There are two ways of creating a virtual function: or Let's understand through an example. Differences between the virtual function and pure virtual function
Next TopicHow to Split strings in C++
|