- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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