Virtual Function in C++
Virtual Function in C++
Virtual Function is one of the advances features of OOPs .Β A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class.
Polymorphism refers to the property by which objects belonging to different classes are able to
respond to the same message, but different forms. An essential requirement of polymorphism is therefore the ability to refer to objects without any regard to their classes.
When we use the same function name in both the base and derived classes, the function in the bas
class is declared as virtual using the keyword virtual preceding its normal declaration.
CODE :
#include <iostream>
using namespace std;
class Base {
public:
virtual void print() {
cout << "Base Function" << endl;
}
};
class Derived : public Base {
public:
void print() override {
cout << "Derived Function" << endl;
}
};
int main() {
Derived derived1;
// pointer of Base type that points to derived1
Base* base1 = &derived1;
// calls member function of Derived class
base1->print();
return 0;
}
OUTPUT :
Derived Function
Topics Covered :
- virtual function in c++
- virtual functions
- virtual functions tutorial
- function
- object-oriented programming
- programming
Thanks for reading this blog. Hope you get satisfied with the blog and definitely this blog must have valued your time and effort of reading.
Take a time to connect our other digital creations such as Instagram , Facebook and Youtube.
Β Social MediaΒ LinksΒ ofΒ Tech DCodeΒ :
Β YouTube :Β https://www.youtube.com/channel/UCjJnEdeugftBwQ3yMuD4B_A
Β Instagram :Β https://www.instagram.com/thetechdcode/
Β Facebook Page :Β https://www.facebook.com/thetechdcode
Β Twitter :Β https://twitter.com/thetechdcode
Β Telegram Channel :Β https://t.me/thetechdcode
Β Tech DCode Linktree :Β https://linktr.ee/thetechdcode
Β My Personal Handles :Β https://linktr.ee/virtualshivamin
Β Social Media LinksΒ ofΒ SHIVAM SINGHΒ (OWNER) :
Β Instagram :Β https://www.instagram.com/virtualshivamin/
Β Facebook Page :Β https://www.facebook.com/virtualshivamin/
Β Twitter :Β https://twitter.com/virtualshivamin/
Β Personal Linktree :Β https://linktr.ee/virtualshivaminΒ