- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Inline virtual function in C++
Virtual functions in C++ use 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 the runtime.
The main use of the virtual function is to achieve Runtime Polymorphism. The inline functions are used to increase the efficiency of the code. The code of inline function gets substituted at the point of an inline function call at compile time, whenever the inline function is called.
Whenever a virtual function is called using base class reference or pointer it cannot be inlined, but whenever called using the object without reference or pointer of that class, can be inlined because the compiler knows the exact class of the object at compile time.
Example Code
#include<iostream> using namespace std; class B { public: virtual void s() { cout<<" In Base \n"; } }; class D: public B { public: void s() { cout<<"In Derived \n"; } }; int main(void) { B b; D d; // An object of class D B *bptr = &d;// A pointer of type B* pointing to d b.s();//Can be inlined as s() is called through object of class bptr->s();// prints"D::s() called" //cannot be inlined, as virtualfunction is called through pointer. return 0; }
Output
In Base In Derived
- Related Articles
- Virtual Function in C++
- Difference between a virtual function and a pure virtual function in C++
- What is an inline function in C language?
- What happens when a virtual function is called inside a non-virtual function in C++
- Default arguments and virtual function in C++
- Difference Between Virtual and Pure Virtual Function
- Inline Functions in C++
- When to use inline function and when not to use it in C/C++?
- When to use an inline function in Kotlin?
- How to call a virtual function inside constructors in C++?
- C++ interview questions on virtual function and abstract class
- Why is a C++ pure virtual function initialized by 0?
- Benefits of inline functions in C++?
- When should I write the keyword 'inline' for a function/method in C++?
- Difference Between Inline and Macro in C++
