Open In App

Output of C++ Program | Set 5

Improve
Improve
Like Article
Like
Save
Share
Report

Difficulty Level: Rookie
Predict the output of below C++ programs.
Question 1 
 

C++




#include<iostream>
using namespace std;
 
class Test {
    int value;
public:
    Test(int v);
};
 
Test::Test(int v) {
    value = v;
}
 
int main() {
    Test t[100];
    return 0;
}


Output: 
 

Compiler error

The class Test has one user defined constructor “Test(int v)” that expects one argument. It doesn’t have a constructor without any argument as the compiler doesn’t create the default constructor if user defines a constructor (See this). Following modified program works without any error.
 

C++




#include<iostream>
using namespace std;
 
class Test {
    int value;
public:
    Test(int v = 0);
};
 
Test::Test(int v) {
    value = v;
}
 
int main() {
    Test t[100];
    return 0;
}


Question 2 
 

C++




#include<iostream>
using namespace std;
int &fun() {
  static int a = 10;
  return a;
}
 
int main() {
  int &y = fun();
  y = y +30;
  cout<<fun();
  return 0;
}


Output: 
 

40

The program works fine because ‘a’ is static. Since ‘a’ is static, memory location of it remains valid even after fun() returns. So a reference to static variable can be returned.
Question 3 
 

C++




#include<iostream>
using namespace std;
 
class Test
{
public:
  Test();
};
 
Test::Test()  {
    cout<<"Constructor Called \n";
}
 
int main()
{
    cout<<"Start \n";
    Test t1();
    cout<<"End \n";
    return 0;
}


Output: 
 

Start
End

Note that the line “Test t1();” is not a constructor call. Compiler considers this line as declaration of function t1 that doesn’t receive any parameter and returns object of type Test.
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 : 05 Jan, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads