📘 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

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

Pure virtual function (= 0) का body नहीं होता और override करना ज़रूरी है। ऐसी एक function वाली class abstract class बन जाती है (instantiate नहीं हो सकती)।

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

सारांश

  • Pure virtual function (=0) child classes को implement करने पर मजबूर करता है।
  • Abstract class में कम-से-कम एक pure virtual होता है और instantiate नहीं हो सकती।
← Back to C++ Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

\n