Simple Program for Virtual Functions
On this page (7sections)
Aim
Simple Example Program for virtual functions.
Simple Program for Virtual Functions Algorithm/Steps:
- Step 1: Start the program.
- Step 2: Declare the base class base.
- Step 3: Declare and define the virtual function show().
- Step 4: Declare and define the function display().
- Step 5: Create the derived class from the base class.
- Step 6: Declare and define the functions display() and show().
- Step 7: Create the base class object and pointer variable.
- Step 8: Call the functions display() and show() using the base class object and pointer.
- Step 9: Create the derived class object and call the functions display() and show() using the derived class object and pointer.
- Step 10: Stop the program.
Simple Program for Virtual Functions
#include<iostream.h>
#include<conio.h>
class base {
public:
virtual void show() {
cout << "\n Base class show:";
}
void display() {
cout << "\n Base class display:";
}
};
class drive : public base {
public:
void display() {
cout << "\n Drive class display:";
}
void show() {
cout << "\n Drive class show:";
}
};
void main() {
clrscr();
base obj1;
base *p;
cout << "\n\t P points to base:\n";
p = &obj1;
p->display();
p->show();
cout << "\n\n\t P points to drive:\n";
drive obj2;
p = &obj2;
p->display();
p->show();
getch();
}
Sample Output
P points to Base
Base class display
Base class show
P points to Drive
Base class Display
Drive class Show
How It Works
This C++ program demonstrates Simple Program for Virtual Functions. It first prepares the data it needs, then performs the core operation step by step, and finally prints the output shown in the Sample Output above.
- Declare the variables that hold the program’s data.
- Print the final result to the console so you can compare it with the sample output.
Try changing the input values and re-running the program to see how the output changes — this is the fastest way to understand how the logic behaves.
Related Pages
Learn the concept first, then study the code:
- C++ Programs — Browse all C++ Programs.
Frequently Asked Questions
What does this C++ program do?
It is a C++ example program that demonstrates Simple Program for Virtual Functions, including the complete source code and the expected sample output.
How do I compile and run this C++ program?
Save the code in a `.cpp` file, compile it with `g++ filename.cpp -o program`, then run it with `./program` (or `program.exe` on Windows).
What concepts does this example use?
This example uses user-defined functions, illustrating a common pattern in C++ programming.