📘 Lesson · Lesson 72
Pure Virtual & Abstract Class
Abstract Classes
💡 Note
A pure virtual function (= 0) has no body and must be overridden. A class with one becomes an abstract class (cannot be instantiated).
Example
C++
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() = 0; // pure virtual
};
class Circle : public Shape {
double r;
public:
Circle(double r) : r(r) {}
double area() override { return 3.14 * r * r; }
};
int main() {
Shape* s = new Circle(5);
cout << s->area(); // 78.5
return 0;
}Output:
78.5
78.5
Summary
- A pure virtual function (=0) forces child classes to implement it.
- An abstract class has at least one pure virtual and cannot be instantiated.
Abstract Classes
💡 Note
A pure virtual function (= 0) has no body and must be overridden. A class with one becomes an abstract class (cannot be instantiated).
Example
C++
#include <iostream>
using namespace std;
class Shape {
public:
virtual double area() = 0; // pure virtual
};
class Circle : public Shape {
double r;
public:
Circle(double r) : r(r) {}
double area() override { return 3.14 * r * r; }
};
int main() {
Shape* s = new Circle(5);
cout << s->area(); // 78.5
return 0;
}Output:
78.5
78.5
सारांश
- A pure virtual function (=0) forces child classes to implement it.
- An abstract class has at least one pure virtual and cannot be instantiated.
💻 Live Code Editor
This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.