Output of C++ Program | Set 12

Predict the output of following C++ programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
  
int fun(int a, int b  = 1, int c =2)
{
    return (a + b + c);
}
  
int main()
{
    cout << fun(12, ,2);
    return 0;
}

chevron_right


Output: Compiler Error in function call fun(12, ,2)
With default arguments, we cannot skip an argument in the middle. Once an argument is skipped, all the following arguments must be skipped. The calls fun(12) and fun(12, 2) are valid.





Question 2

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
using namespace std;
  
/* local variable is same as a member's name */
class Test
{
private:
    int x;
public:
    void setX (int x) { Test::x = x; }
    void print() { cout << "x = " << x << endl; }
};
  
int main()
{
    Test obj;
    int x = 40;
    obj.setX(x);
    obj.print();
    return 0;
}

chevron_right


Output:

x = 40

Scope resolution operator can always be used to access a class member when it is made hidden by local variables. So the line “Test::x = x” is same as “this->x = x”



Question 3

filter_none

edit
close

play_arrow

link
brightness_4
code

#include<iostream>
using namespace std;
  
class Test 
{
private:
    int x;
    static int count;
public:
    Test(int i = 0) : x(i) {}
    Test(const Test& rhs) : x(rhs.x) { ++count;  }
    static int getCount() { return count; }
};
  
int Test::count = 0;
  
Test fun() 
{
    return Test();
}
  
int main()
{
    Test a = fun();
    cout<< Test::getCount();
    return 0;
}

chevron_right


Output: Compiler Dependent
The line “Test a = fun()” may or may not call copy constructor. So output may be 0 or 1. If copy elision happens in your compiler, the copy constructor will not be called. If copy elision doesn’t happen, copy constructor will be called. The gcc compiler produced the output as 0.

Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above.



My Personal Notes arrow_drop_up


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.