CodesJava

Easy learning with example program codes

CPP virtual function


A virtual function in CPP is used to perform dynamic linkage or late binding on a function. Late binding is used to resolve a function call during runtime, thus allowing the compiler to bind the function call at runtime after determining the type of object. A virtual function can be simply understood as a member function in base class which is redefined in a derived class and is declared using the virtual keyword.

Example:

#include <iostream.h>  
using namespace std;  
class Base  
{  
public:  
virtual void print()  
{  
cout << "Hey, I am the Base."<<endl;  
}  
};  
class Derived:public Base
{  
public:  
void print()  
{  
cout << "Hey, I was Derived."<<endl;  
}  
};  
int main()  
{  
Base* b;	 
Derived d;	 
b = &d;  
b->print();   
}

Output

Hey, I was Derived.
Posted in CPP   
Sign Up/ Sign In
Ask a Question


Industrial Training

We offers Placement Oriented Training on Java, Spring, JSF, Hibernate, PHP, AngularJS, Angular 4, PLSQL, Oracle BI Publisher etc. We also provides Online training, please mail us at hr@codesjava.com.

Development

We also provides the Development services for Website Development , Java Development, PHP Development, Android App Development etc. You can contact us on hr@codesjava.com.

Copyright © 2018 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki