1. What is a pure virtual function?
Ans. A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration. See the following example.
2. What is abstract class?
Ans. A class which contains atleast one pure virtual function, is known as abstract class. see the following example
in above example, Test is an abstract class because it has a pure virtual function.
Some interesting facts about abstract class
1) We can’t create an object of abstract class.
Compiler Error: cannot declare variable 't' to be of abstract type 'Test' because the following virtual functions are pure within 'Test': note: virtual void Test::show()
2.We can have pointers and references of abstract class type.
For example the following program works fine.
3. If we do not override the pure virtual function in derived class, then derived class also becomes abstract class.
The following example demonstrates the same.
Compiler Error: cannot declare variable 'd' to be of abstract type 'Derived' because the following virtual functions are pure within 'Derived': virtual void Base::show()
3. What is the output of this program?
Explanation: In this program, we are calculating the area of rectangle and
triangle by using abstract class.
4. What is the output of this program?
Explanation: In this program, We are executing these based on the condition given in array. So it is printing as 212.
5. What is the output of this program?
GeeksForGeeks is awesome
Explanation: In this program, We are combining the two statements from two classes and printing it by using abstract class.
- Pure Virtual Functions and Abstract Classes in C++
- What happens when a virtual function is called inside a non-virtual function in C++
- Virtual base class in C++
- Virtual Function in C++
- Default arguments and virtual function
- Friend class and function in C++
- Can we access private data members of a class without using a member or a friend function?
- Commonly Asked C++ Interview Questions | Set 1
- Commonly Asked OOP Interview Questions | Set 1
- Commonly Asked C++ Interview Questions | Set 2
- C++ Interview questions based on constructors/ Destructors.
- Virtual Destructor
- Can virtual functions be private in C++?
- Can static functions be virtual in C++?
- Virtual destruction using shared_ptr in C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.