×

C++ Tutorial

C++ Data types

C++ Operators & Keywords

C++ Conditional Statements

C++ Functions

C++ 'this' Pointer, References

C++ Class & Objects

C++ Constructors & Destructors

C++ Operator overloading

C++ 11 (Advance C++)

C++ Preparation

C++ Header Files & Functionsr

Data Structure with C++

C++ - Miscellaneous

C++ Programs

C++ Function Overloading | Find output programs | Set 3

This section contains the C++ find output programs with their explanations on C++ Function Overloading (set 3).
Submitted by Nidhi, on June 25, 2020

Program 1:

#include <iostream>
using namespace std;

class Test {
public:
    void fun()
    {
        cout << "Fun() called" << endl;
    }
    void fun(int num)
    {
        cout << num << endl;
    }
};

int main()
{
    Test T;

    T.fun('A');

    return 0;
}

Output:

65

Explanation:

Here, we created a class Test that contains two member functions fun() that are overloaded.

Now, look to the main() function. Here we created an object T. And, called function fun(), but there is no exact match of function fun() is available in the class. But integer and character have the same internal structure that's why it called the function fun() with character argument and print ASCII value of 'A' that is 65.

Program 2:

#include <iostream>
using namespace std;

struct Test {
    void fun()
    {
        cout << "Fun() called" << endl;
    }
    void fun(int num)
    {
        cout << num << endl;
    }
};

int main()
{
    Test T;

    T.fun(100);

    return 0;
}

Output:

100

Explanation:

Here, we created a structure Test that contains two member functions fun() that are overloaded. By default the members of a structure are public.

Now, look to the main() function. Here we created a structure variable of T.  Then we called function fun() with an integer argument, then "100" will be printed on the console screen.

Program 3:

#include <iostream>
using namespace std;

struct Test {
    void fun()
    {
        cout << "Fun() called" << endl;
    }
    void fun(int num)
    {
        cout << num << endl;
    }
} * T;

int main()
{
    T.fun(100);

    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:17:7: error: request for member ‘fun’ in ‘T’, 
which is of pointer type ‘Test*’ (maybe you meant to use ‘->’ ?)
     T.fun(100);
       ^~~

Explanation:

This code will generate an error because, here, we created the pointer to a structure, but we called a member of a structure using "." Operator, as we know that, first we need to assign the address of structure variable and then we need to use referential operator "->" to access the members of a structure using the pointer.





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.