📘 Lesson · Lesson 72
Pure Virtual & Abstract Class
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
Is page ke program yahan ready hain — chalाएं, badlें aur seekhें. Bina kuch install kiye.
Powered by OneCompiler. Editor mein code apne aap aa jata hai — Run dabaakर output dekhें.
Agar load na ho to naye tab mein kholें.