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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
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
- Function overloading and const keyword
- Function Overloading and float in C++
- Does C support function overloading?
- Default Assignment Operator and References
- When does compiler create default and copy constructors in C++?
- How to Count Variable Numbers of Arguments in C?
- When do we pass arguments by reference or pointer?
- Variable length arguments for Macros
- Command line arguments in C/C++
- Command line arguments example in C
- C++ | Operator Overloading | Question 10
- C++ | Operator Overloading | Question 2

