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

Ad: Are you a blogger? Join our Blogging forum.





Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates


© https://www.includehelp.com some rights reserved.