C++ Constructors Question:
Download Questions PDF

What is constructor in C++?


Constructors allow initialization of objects at the time of their creation. Constructor function is a special function that is a member of the class and has same name as that of the class. An object’s constructor is automatically called whenever the object is created (statically or dynamically). Constructors are always public. They are used to make initializations at the time of object creation.

Consider following example of a stack class:

#include <iostream>
using namespace std;
class stack
int top, bottom;
int data[20];
stack() //constructor function
top = bottom;
cout <<”Inside Stack Constructor: Stack
int stackfull()
return ((top == max – 1)?1:0);
int stackempty()
return (top == bottom)?1:0);
void push(int no)
cout<<”Stack is full”;
data[++top] = no;
int pop()
cout<<”Nothing to pop.. Stack is Empty!”;

int main()
int i, no;
stack st; //object is created; hence constructor is
invoked- stack initialization done
cout <<” Entered Main\n”;
for(i = 0; i < 10; i++)
no = s.pop();
cout <<”The popped element is:”<
return 0;

The o/p of the program would be:

Entered Main
Inside Stack Constructor: Stack initialized
The popped element is: 9

As seen above, the stack object is initialized automatically at the time of creation by the constructor. So we don’t need to write and invoke initialization functions explicitly.

Download C++ Constructors Interview Questions And Answers PDF

Previous QuestionNext Question
What is virtual constructor?Can you please explain Explain constructors and destructors?