Skip to content
Related Articles

Related Articles

Improve Article

C++ | Constructors | Question 15

  • Last Updated : 28 Jun, 2021
Geek Week




#include<iostream>
using namespace std;
   
class Test
{
public:
  Test();
};
   
Test::Test()  {
    cout << " Constructor Called. ";
}
   
void fun() {
  static Test t1;
}
   
int main() {
    cout << " Before fun() called. ";
    fun();
    fun();
    cout << " After fun() called. ";  
    return 0;
}

(A) Constructor Called. Before fun() called. After fun() called.
(B) Before fun() called. Constructor Called. Constructor Called. After fun() called.
(C) Before fun() called. Constructor Called. After fun() called.
(D) Constructor Called. Constructor Called. After fun() called.Before fun() called.


Answer: (C)

Explanation: Notice within the function fun(), the variable t1 is declared static. Thus the Test::Test constructor is called only once for the lifetime of the program.
For more information, please see Static Keyword in C++ and read the section “Static variables in a Function.”


Quiz of this Question

Take a step-up from those “Hello World” programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.
My Personal Notes arrow_drop_up
Recommended Articles
Page :