
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
How are virtual functions implemented in C++?
Virtual functions in C++ used to create a list of base class pointers and call methods of any of the derived classes without even knowing kind of derived class object. Virtual functions are resolved late, at runtime.
Here is an implementation of virtual function in C++ program −
Example
#include <iostream> using namespace std; class B { public: virtual void s() { //virtual function cout<<" In Base \n"; } }; class D: public B { public: void s() { cout<<"In Derived \n"; } }; int main(void) { D d; // An object of class D B *b= &d; // A pointer variable of type B* pointing to d b->s(); // prints"D::s() called" return 0; }
Output
In Derived
- Related Articles
- What are virtual functions in C#?
- What are Java methods equivalent to C# virtual functions?
- Virtual functions in derived classes in C++
- Calling virtual functions inside constructors in C++
- Virtual Functions and Runtime Polymorphism in C++
- Pure Virtual Functions and Abstract Classes in C++
- How are dictionaries implemented in Python?
- How is encapsulation implemented in C#?
- Can a C++ virtual functions have default parameters?
- What is the difference between virtual and abstract functions in C#?
- What are the interfaces implemented by Array class in C#?
- How Can MySQL virtual GENERATED COLUMNS work with built-in functions?
- How arrays are passed to functions in C/C++
- What are static member functions in C#?
- What are Local functions in C# 7.0?

Advertisements