Skip to content
Related Articles

Related Articles

Output of C++ Program | Set 5
  • Difficulty Level : Medium
  • Last Updated : 10 Jul, 2018

Difficulty Level: Rookie

Predict the output of below C++ programs.

Question 1




#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.






#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




#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




#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 recieve 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

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.

My Personal Notes arrow_drop_up
Recommended Articles
Page :