C++ | Function Overloading and Default Arguments | Question 4
Predict the output of following C++ program.
include<iostream> using namespace std; class Test { protected: int x; public: Test (int i):x(i) { } void fun() const { cout << "fun() const " << endl; } void fun() { cout << "fun() " << endl; } }; int main() { Test t1 (10); const Test t2 (20); t1.fun(); t2.fun(); return 0; } |
(A) Compiler Error
(B) fun()
fun() const
(C) fun() const
fun() const
(D) fun()
fun()
Answer: (B)
Explanation: The two methods ‘void fun() const’ and ‘void fun()’ have same signature except that one is const and other is not. Also, if we take a closer look at the output, we observe that, ‘const void fun()’ is called on const object and ‘void fun()’ is called on non-const object.
C++ allows member methods to be overloaded on the basis of const type. Overloading on the basis of const type can be useful when a function return reference or pointer. We can make one function const, that returns a const reference or const pointer, other non-const function, that returns non-const reference or pointer. See following for more details.
Function overloading and const keyword
Quiz of this Question
Recommended Posts:
- C++ | Function Overloading and Default Arguments | Question 5
- C++ | Function Overloading and Default Arguments | Question 2
- C++ | Function Overloading and Default Arguments | Question 3
- C++ | Function Overloading and Default Arguments | Question 5
- Default arguments and virtual function
- Templates and Default Arguments
- Some Interesting facts about default arguments in C++
- getopt() function in C to parse command line arguments
- Does C support function overloading?
- Function Overloading and float in C++
- Function overloading and const keyword
- C++ | Operator Overloading | Question 5
- C++ | Operator Overloading | Question 6
- C++ | Operator Overloading | Question 7
- C++ | Operator Overloading | Question 10



