Search This Blog
Welcome to 1printf(), your ultimate destination for C, C++, Linux, Data Structures, and Microcontroller programming! π πΉLearn advanced coding techniques in C& C++ πΉMaster Linux internals & shell scripting πΉDeep dive into Data Structures & Algorithms πΉExplore Embedded Systems & Microcontrollers (8051,UART, RTOS) πΉGet hands-on coding tutorials, project ideas,and interview preparation tips Whether you're a beginner or an experienced programmer, this channel will help you
Featured
- Get link
- X
- Other Apps
C++ Abstract Class and Pure Virtual Function Example
✅ C++ Program: Abstract Class and Pure Virtual Functions
#include <iostream>
using namespace std;
// Abstract class
class Animal {
public:
// Pure virtual function
virtual void sound() = 0;
};
// Derived class Dog
class Dog : public Animal {
public:
void sound() override {
cout << "Dog barks πΆ\n";
}
};
// Derived class Cat
class Cat : public Animal {
public:
void sound() override {
cout << "Cat meows π±\n";
}
};
int main() {
// Animal a; ❌ ERROR: object of abstract class not allowed
Animal *ptr; // ✅ Abstract class pointer
Dog d;
Cat c;
ptr = &d;
ptr->sound(); // Calls Dog’s version
ptr = &c;
ptr->sound(); // Calls Cat’s version
}
π Explanation:
This program demonstrates the use of abstract classes and pure virtual functions in C++. Key points:
Animalis an abstract class because it has a pure virtual functionsound().- You cannot create objects of abstract classes.
- You can create pointers of abstract class type and point them to derived objects.
- Runtime polymorphism ensures the correct function is called based on the object assigned.
π§Ύ Sample Output:
Dog barks πΆ Cat meows π±
π Keywords:
C++ abstract class, pure virtual function, runtime polymorphism, OOPs in C++, C++ class hierarchy
π Hashtags:
#CPlusPlus #AbstractClass #Polymorphism #OOP #CppInterview #VirtualFunctions
π Search Description:
This C++ program demonstrates abstract classes and pure virtual functions using Animal, Dog, and Cat classes. Explains runtime polymorphism with sample output.
Popular Posts
C++ Program for Hybrid Inheritance (All Types Together)
- Get link
- X
- Other Apps
C++ Program for Function Overloading Example
- Get link
- X
- Other Apps
Comments
Post a Comment