Open In App
Related Articles

Output of C++ Program | Set 12

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report
Predict the output of following C++ programs. Question 1
#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;
}

                    
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
#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;
}

                    
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
#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;
}

                    
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.

Last Updated : 28 Sep, 2018
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads