What is a constructor?
- 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:”<<no;
return 0;
}
- The output 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.
What is a constructor?
A constructor is a special member function whose task is to initialize objects of its classes. Its name is same as that of its class. It is invoked when an object of that class is created.
Explain constructors and destructors.
- Constructors are the member functions of the class that executes automatically whenever an object is created. Constructors have the same name as the class. Constructors initialize the class. Constructors can’t have return type. Destructors are called when the objects are destroyed.
- Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted. A destructor takes no arguments and has no return type.
What is a constructor?
A constructor allocates space for an object and initializes it. Constructors always have the same name as their class. A class may have more than one constructor.