![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Can a C++ virtual functions have default parameters?
Yes, C++ virtual functions can have default parameters.
Example Code
#include<iostream> using namespace std; class B { public: virtual void s(int a = 0) { cout<<" In Base \n"; } }; class D: public B { public: virtual void s(int a) { cout<<"In Derived, a="<<a; } }; int main(void) { D d; // An object of class D B *b = &d;// A pointer of type B* pointing to d b->s();// prints"D::s() called" return 0; }
Output
In Derived, a=0
In this output, we observe that, s() of derived class is called and default value of base class s() is used.
Default arguments do not participate in signature of functions. So signatures of s() in base class and derived class are considered same, hence base class’s s() is overridden. Default value is used at compile time. When compiler checks that an argument is missing in a function call, it substitutes the default value given. Therefore, in the above program, value of x is substituted at compile time, and at run time derived class’s s() is called. Value of a is substituted at compile time, and at run time derived class’s s() is called.
Advertisements