Output of C++ Program | Set 5

Difficulty Level: Rookie

Predict the output of below C++ programs.

Question 1

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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.



filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right




Question 2

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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



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.