Constructors
A constructor is a member function of a class that is automatically called when object of a class is created.
It has same name as that of class name.
It has no return type even void.
Primary job of Constructor is used to initialize values to different data members of class.
It has three types - default , parameterized and copy constructor.
-> Following code snippet is a example of constructor in a class.
class student {
public:
int age;
int rollno;
student() //constructor
{
age=10;
rollno=15;
}
void display()
{
cout<<age<<" "<<rollno;
}
}; //class ends here
int main() // main function
{
student s; //object of student is created so student constructor will automatically get invoked
s.display(); // function to display details
return 0;
}
// code in c++ language
Destructors
A destructor is used to destroy the objects that have been created by a constructor.
It has same name as that of class name.
' ~ ' Symbol is used in creating a destructor.
It takes no arguments and have no return types.
Primary job is to perform a clean up tasks (like closing a file , deallocating and releasing memory area) automatically.
class student {
public:
int age;
int rollno;
student() //constructor
{
age=10;
rollno=15;
}
~student() //destructor
{
cout<<" Destructor called";
}
void display()
{
cout<<age<<" "<<rollno;
}
}; //class ends here
int main() // main function
{
student s; //object of student is created so student constructor will automatically get invoked
s.display(); // function to display details
return 0;
}
// code in c++ language
ย