The Wayback Machine - https://web.archive.org/web/20241002071241/https://www.geeksforgeeks.org/default-arguments-and-virtual-function-in-cpp/
Open In App

Default Arguments and Virtual Function in C++

Last Updated : 03 Jan, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Default Arguments are the values provided during function declaration, such that values can be automatically assigned if no argument is passed to them. In case any value is passed the default value is overridden and it becomes a parameterized argument.

Virtual function is a member function that is declared within a base class and is redefined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. A virtual function also falls under runtime polymorphism.

To see the combined application of default arguments with virtual functions let’s take a sample

Example:

CPP




// C++ program to demonstrate how default arguments
// and virtual function are used together
#include <iostream>
using namespace std;
 
// Initialization of base class
class Base {
public:
    // Initialization of virtual function
    virtual void fun(int x = 0)
    {
        cout << "Base::fun(), x = " << x << endl;
    }
};
 
// Initialization of Derived class
class Derived : public Base {
public:
    // NOTE this virtual function will take an argument
    // But haven't initialized yet
    virtual void fun(int x)
    {
        cout << "Derived::fun(), x = " << x << endl;
    }
};
 
// Driver Code
int main()
{
    Derived d1; // Constructor
 
    // Base class pointer which will
    // Edit value in memory location of
    // Derived class constructor
    Base* bp = &d1;
   
    bp->fun(); // Calling a derived class member function
   
    return 0; // Returning 0 means the program
              // Executed successfully
}


Output:

Derived::fun(), x = 0

If we take a closer look at the output, we observe that the ‘fun()‘ function of the derived class is called, and the default value of the base class ‘fun()‘ function is used. 

Default arguments do not participate in the signature( function’s name, type, and order) of functions. So signatures of the ‘fun()‘ function in the base class and derived class are considered the same, hence the ‘fun()‘ function of the base class is overridden. Also, the default value is used at compile time. When the compiler sees an argument missing in a function call, it substitutes the default value given. Therefore, in the above program, the value of x is substituted at compile-time, and at run-time derived class’s ‘fun()‘ function is called. 

Example:

CPP




// C++ program To demonstrate how default arguments
// and virtual function are used together
#include <iostream>
using namespace std;
 
class Base {
public:
    virtual void fun(int x = 0)
    {
        cout << "Base::fun(), x = " << x << endl;
    }
};
 
class Derived : public Base {
public:
    virtual void fun(int x = 10) // NOTE THIS CHANGE
    {
        cout << "Derived::fun(), x = " << x << endl;
    }
};
 
int main()
{
    Derived d1; // Constructor
 
    // Base class pointer which will
    // Edit value in memory location of
    // Derived class constructor
    Base* bp = &d1;
 
    bp->fun(); // Calling a derived class member function
 
    return 0; // Returning 0 means the program
              // Executed successfully
}


Output

Derived::fun(), x = 0

The output of this program is the same as the previous program. The reason is the same, the default value is substituted at compile time. The fun() is called on ‘bp’ which is a pointer of Base type. So compiler substitutes 0 (not 10).



Previous Article
Next Article

Similar Reads

Templates and Default Arguments
Default parameters for templates in C++: Like function default arguments, templates can also have default arguments. For example, in the following program, the second parameter U has the default value as char. #include<iostream> using namespace std; template<class T, class U = char> class A { public: T x; U y; }; int main() { A<char
1 min read
Default Arguments in C++
A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden. 1) The following is a simple C++ example to demonstrate the use of default arguments. Here, we don't have to w
5 min read
Some Interesting facts about default arguments in C++
Predict the output of following C++ programs. 1) #include <iostream> void init(int a=1, int b=2, int c=3); int main() { init(); return 0; } void init(int a=1, int b=2, int c=3) { std::cout << a << ' ' << b << ' ' << c; } The above program looks correct at first glance but will fail in compilation. If function use
1 min read
Difference between Virtual function and Pure virtual function in C++
Virtual Function in C++ A virtual function is a member function which is declared within a base class and is re-defined(Overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class’s version of the function. Pu
2 min read
What happens when a virtual function is called inside a non-virtual function in C++
Predict the output of the following simple C++ program without any virtual function. C/C++ Code #include &lt;iostream&gt; using namespace std; class Base { public: void print() { cout &lt;&lt; &quot;Base class print function \n&quot;; } void invoke() { cout &lt;&lt; &quot;Base class invoke function \n&quot;;
2 min read
How Does Default Virtual Behavior Differ in C++ and Java?
Let us discuss how the default virtual behavior of methods is opposite in C++ and Java. It is very important to remember that in the C++ language class member methods are non-virtual by default. They can be made virtual by using virtual keywords. For example, Base::show() is non-virtual in following program and program prints "Base::show() called".
3 min read
Difference between virtual function and inline function in C++
Virtual function: Virtual function is a member function which is declared within a base class and is redefined by a derived class. Inline function: Inline function is a normal function which is defined by the keyword inline, it is a short function which is expanded by the compiler and its arguments are evaluated only once. The syntax of defining th
2 min read
Difference Between Friend Function and Virtual Function in C++
A friend class can access private and protected members of other classes in which it is declared as friend. It is sometimes useful to allow a particular class to access private members of other classes. Just likely, a friend function is a function that is declared outside the scope of a class. This function can be invoked like a normal function and
3 min read
Template non-type arguments in C++
Prerequisite: Templates in C++ Generally, a C++ template, with a single argument looks like this: template<typename template_name> But it has been seen that a template can have multiple arguments. The syntax for the same would be: template<class T1, class T2, class T3, ........., class Tn> where, n is the number of arguments. It is also
3 min read
When Do We Pass Arguments by Reference or Pointer in C++?
In C++, we can pass arguments to a function as a value, reference (or pointer). Each method has its unique benefits and uses. In this article, we will discuss the application or cases where we should pass the arguments by reference or a pointer. But first, let’s quickly revisit the definitions of pointers and references. Pointers in C++ Pointers ar
4 min read
Command Line Arguments in C++
Command-line arguments are arguments that are passed to a program when it is executed from the command line or terminal. They are provided in the command-line shell of operating systems with the program execution command. The main function of C++ generally can have the following signature: int main(){ // Suitable Code return 0; } But to pass comman
4 min read
C++ interview questions on virtual function and abstract class
1. What is a pure virtual function ? Ans. A pure virtual function (or abstract function) in C++ is a virtual function for which we don’t have implementation, we only declare it. A pure virtual function is declared by assigning 0 in declaration. See the following example. [GFGTABS] CPP // An abstract class class Test { // Data members of class publi
4 min read
When Does Compiler Create Default and Copy Constructors in C++?
A constructor is a special type of member function of a class that initializes objects of a class. In C++, Constructor is automatically called when an object(instance of a class) is created. There are 3 types of constructors in C++ Default ConstructorCopy constructorParameterized ConstructorIn C++, the compiler creates a default constructor if we d
3 min read
Default Assignment Operator and References in C++
We have discussed assignment operator overloading for dynamically allocated resources here. In this article, we discussed that when we don't write our own assignment operator, the compiler creates an assignment operator itself that does shallow copy and thus causes problems. The difference between shallow copy and deep copy becomes visible when the
2 min read
Virtual Function in C++
A virtual function (also known as virtual methods) is a member function that is declared within a base class and is re-defined (overridden) by a derived class. When you refer to a derived class object using a pointer or a reference to the base class, you can call a virtual function for that object and execute the derived class's version of the meth
6 min read
Default values in a Map in C++ STL
Prerequisite: Map in STLA map is a container which is used to store a key-value pair. By default, In Primitive datatypes such as int, char, bool, float in C/C++ are undefined if variables are not initialized, But a Map is initially empty when it is declared. When this map is accessed with the [ ] (e.g map<int,int> mpp; mpp[1]; ) if the key is
2 min read
Is body of a Default Constructor blank in C++?
The answer to this question depends upon 2 scenarios: Scenario 1: When there is a Virtual function in the program: In this scenario, compiler automatically creates virtual table(known as V-Table) and VVPTR(Virtual Void Pointer). V-Table contains the virtual method calls whereas VVPTR contain the address of virtual methods which are present in V-Tab
2 min read
Default Methods in C++ with Examples
If we write a class that has no methods in it, and the class does not inherit from another class, the compiler will add six methods to it automatically. The methods which can be automatically generated by the compiler are: Default Constructor: It is equivalent to an empty default constructor. The default constructor is a constructor which can be ca
6 min read
C++ default constructor | Built-in types for int(), float, double()
A constructor without any arguments or with default values for every argument is treated as the default constructor. C++ allows even built-in types (primitive types) to have default constructors. The function style cast int() is analogous(similar in some way) to casting 0 to the required type.It will be called by the compiler when in need(precisely
2 min read
Default Constructors in C++
A constructor without any arguments or with the default value for every argument is said to be the Default constructor. A constructor that has zero parameter list or in other sense, a constructor that accepts no arguments is called a zero-argument constructor or default constructor. If default constructor is not defined in the source code by the pr
4 min read
Does C++ compiler create default constructor when we write our own?
No, the C++ compiler doesn't create a default constructor when we define any type of constructor manually in the class. ExplanationThe default constructor is used to create an object's instance without any arguments. In C++, the compiler implicitly creates a default constructor for every class which doesn't have user defined constructor so that at
2 min read
Virtual Functions and Runtime Polymorphism in C++
A virtual function is a member function that is declared in the base class using the keyword virtual and is re-defined (Overridden) in the derived class. It tells the compiler to perform late binding where the compiler matches the object with the right called function and executes it during the runtime. This technique falls under Runtime Polymorphi
8 min read
Pure Virtual Functions and Abstract Classes in C++
Sometimes implementation of all functions cannot be provided in a base class because we don't know the implementation. Such a class is called an abstract class.For example, let Shape be a base class. We cannot provide the implementation of function draw() in Shape, but we know every derived class must have an implementation of draw(). Similarly, an
6 min read
Virtual Functions in Derived Classes in C++
A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class's version of the function. In C++, once a member function is declared as a virtua
2 min read
Target Corporation Interview Experience | On-Campus Virtual Hiring
Round 1 - Online test This round has MCQ s regrading English reading comprehension, Reasoning, logical, Quantitative(Numerical) and technical questions. Technical questions were related to computer science domain. This round also has 2 coding questions: Counting the duplicate elements in an arrayOptimal oil flow problem Both questions had 2 public
3 min read
ARM Interview Experience for Intern (On-Campus Virtual 2020)
ARM talent acquisition team visited our campus virtually for an intern role in the verification domain. There were totally 3 rounds, Round 1 (Written Test) : 30 Aptitude (Time & Work, Time and Distance, percentages, profit and loss, SI & CI covered all major topics in aptitude)70 Technical (Digital, C basics & Guessing the output, OS co
2 min read
Can Static Functions Be Virtual in C++?
In C++, a static member function of a class cannot be virtual. Virtual functions are invoked when you have a pointer or reference to an instance of a class. Static functions aren't tied to the instance of a class but they are tied to the class. C++ doesn't have pointers-to-class, so there is no scenario in which you could invoke a static function v
1 min read
Virtual Destructor
Deleting a derived class object using a pointer of base class type that has a non-virtual destructor results in undefined behavior. To correct this situation, the base class should be defined with a virtual destructor. For example, the following program results in undefined behavior. C/C++ Code // CPP program without virtual destructor // causing u
2 min read
Advanced C++ | Virtual Copy Constructor
In the virtual constructor idiom we have seen the way to construct an object whose type is not determined until runtime. Is it possible to create an object without knowing it's exact class type? The virtual copy constructor address this question.Sometimes we may need to construct an object from another existing object. Precisely the copy constructo
5 min read
Can Virtual Functions be Inlined in C++?
Virtual functions are member functions that are declared in the base class using the keyword virtual and can be overridden by the derived class. They are used to achieve Runtime polymorphism or say late binding or dynamic binding. Inline functions are used to replace the function calling location with the definition of the inline function at compil
2 min read
Article Tags :
Practice Tags :