Answers

Question and Answer:

  Home  C++ Constructors

⟩ 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

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 Mainn”;

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.

 258 views

More Questions for you: