
- 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
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.
- Related Articles
- What is the difference between default and rest parameters in JavaScript functions?
- Default virtual behavior in C++ vs Java
- Default arguments and virtual function in C++
- What are virtual functions in C#?
- How many parameters can a lambda expression have in Java?
- What are default-parameters for function parameters in JavaScript?
- Calling virtual functions inside constructors in C++
- Virtual Functions and Runtime Polymorphism in C++
- Virtual functions in derived classes in C++
- How are virtual functions implemented in C++?
- What is “Parameters without defaults after default parameters in JavaScript”
- Why C++ does not have a virtual constructor?
- What are Default parameters in JavaScript?
- Pure Virtual Functions and Abstract Classes in C++
- How does default virtual behavior differ in C++ and Java?

Advertisements