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