- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Pure Virtual Functions and Abstract Classes in C++
A pure virtual function is a virtual function in C++ for which we need not to write any function definition and only we have to declare it. It is declared by assigning 0 in the declaration.
An abstract class is a class in C++ which have at least one pure virtual function.
-
Abstract class can have normal functions and variables along with a pure virtual function.
-
Abstract class cannot be instantiated, but pointers and references of Abstract class type can be created.
-
Abstract classes are mainly used for Upcasting, so that its derived classes can use its interface.
-
If an Abstract Class has derived class, they must implement all pure virtual functions, or else they will become Abstract too.
-
We can’t create object of abstract class as we reserve a slot for a pure virtual function in Vtable, but we don’t put any address, so Vtable will remain incomplete.
Example Code
#include<iostream> using namespace std; class B { public: virtual void s() = 0; // Pure Virtual Function }; class D:public B { public: void s() { cout << "Virtual Function in Derived class\n"; } }; int main() { B *b; D dobj; b = &dobj; b->s(); }
Output
Virtual Function in Derived class
To Continue Learning Please Login
Login with Google