C++ Constructors Question:

What is constructor in C++?

Tweet Share WhatsApp

Answer:

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
initialized”;
}
int stackfull()
{
return ((top == max – 1)?1:0);
}
int stackempty()
{
return (top == bottom)?1:0);
}
void push(int no)
{
if(stackfull())
cout<<”Stack is full”;
else
data[++top] = no;
}
int pop()
{
if(stackempty())
cout<<”Nothing to pop.. Stack is Empty!”;
else
return(data[top--];
}
};

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++)
st.push(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 PDF Read All 51 C++ Constructors Questions
Previous QuestionNext Question
What is virtual constructor?Can you please explain Explain constructors and destructors?