Skip to content
Related Articles

Related Articles

Improve Article

C++ | Function Overloading and Default Arguments | Question 4

  • Last Updated : 28 Jun, 2021

Predict the output of following C++ program.

using namespace std;
class Test
    int x;
    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);;;
    return 0;

(A) Compiler Error
(B) fun()
fun() const

(C) fun() const
fun() const

(D) 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

Want to learn from the best curated videos and practice problems, check out the C Foundation Course for Basic to Advanced C.
My Personal Notes arrow_drop_up
Recommended Articles
Page :