📘 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

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

सारांश

  • A pure virtual function (=0) forces child classes to implement it.
  • An abstract class has at least one pure virtual and cannot be instantiated.
← Back to C++ Tutorial
🔗

Share this topic with a friend

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

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

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

💻 लाइव कोड एडिटर

इस पेज के प्रोग्राम यहीं तैयार हैं — चलाएँ, बदलें और सीखें। कुछ भी इंस्टॉल किए बिना।
OneCompiler द्वारा संचालित। कोड एडिटर में अपने आप आ जाता है — Run दबाकर आउटपुट देखें। अगर एडिटर न खुले तो नए टैब में खोलें.