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++ Program Example on Virtual Function and Runtime Polymorphism
✅ C++ Program to Demonstrate Virtual Function and Runtime Polymorphism
#include <iostream>
using namespace std;
class Base {
public:
// Virtual function
virtual void display() {
cout << "Display from Base class\n";
}
};
class Derived : public Base {
public:
void display() {
cout << "Display from Derived class\n";
}
};
int main() {
Base *ptr; // Base class pointer
Derived obj; // Derived class object
ptr = &obj;
// Because 'display' is virtual, Derived version is called
ptr->display();
return 0;
}
๐ Explanation:
This program demonstrates runtime polymorphism in C++ using a virtual function.
display()is declared asvirtualinside theBaseclass.- The
Derivedclass overrides thedisplay()function. - A
Baseclass pointer is used to calldisplay()on aDerivedobject. - Because of dynamic binding, the
Derivedversion executes at runtime.
๐งพ Sample Output:
Display from Derived class
๐ Keywords:
C++ virtual function example, runtime polymorphism, OOPs in C++, base and derived class example, dynamic binding
๐ Hashtags:
#CPlusPlus #OOPs #VirtualFunction #RuntimePolymorphism #Programming
๐ Search Description:
Learn how virtual functions enable runtime polymorphism in C++. This example demonstrates how a base class pointer can call a derived class function using the virtual keyword.
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