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

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

Program 1:

#include <iostream>
using namespace std;

void print()
{
    cout << "****" << endl;
}

void print(int NUM, char ch)
{

    for (int i = 0; i < NUM; i++)
        cout << ch;
    cout << endl;
}

int main()
{
    short num = 4;

    print(num, '@');

    return 0;
}

Output:

@@@@

Explanation:

Here, we overloaded print() function,

void print();
void print(int NUM,char ch);

Declarations for overloaded print() function are given below,

In the main() function we passed a short variable instead of int variable, then it will call the function with int argument. Because downgrading of type is possible to call overloaded function.

Program 2:

#include <iostream>
using namespace std;

void print()
{
    cout << "****" << endl;
}

void print(short NUM, char ch)
{

    for (int i = 0; i < NUM; i++)
        cout << ch;
    cout << endl;
}

int main()
{
    int num = 4;

    print(num, '@');

    return 0;
}

Output:

@@@@

Explanation:

Here, we overloaded print() function.

void print();
void print(short NUM,char ch);

Declarations for overloaded print() function are given below,

In the main() function we passed int variable instead of short variable, then it will call the function with short argument. Because similar to downgrading, upgrading of type is also possible to call overloaded function.

Program 3:

#include <iostream>
using namespace std;

class Test {
    void print()
    {
        cout << "****" << endl;
    }

    void print(short NUM, char ch)
    {
        for (int i = 0; i < NUM; i++)
            cout << ch;
        cout << endl;
    }
};

int main()
{
    short num = 4;
    Test T;

    T.print(num, '@');

    return 0;
}

Output:

main.cpp: In function ‘int main()’:
main.cpp:23:21: error: ‘void Test::print(short int, char)’ is private within this context
     T.print(num, '@');
                     ^
main.cpp:10:10: note: declared private here
     void print(short NUM, char ch)
          ^~~~~

Explanation:

This code will generate an error because, in the class Test, we did not specify any access modifier, then by default all members functions of class Test are private. So, it will generate an error because we cannot access private members outside the class.





Comments and Discussions!

Load comments ↻





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