Constructors
Constructors
Constructor is the process to use the class and function is being used in easy way.
Constructor
A constructor is used to initialize the data member of a class. There are three types of constructor:
- Default constructor
- Parameterized constructor
- Copy constructor
- A constructor having zero arguments is called as default constructor.
- A constructor that passes one or more number of arguments is called as parameterized constructor.
Example of constructor
class abc
{
private:
int x;
public:
abc() //constructor defined
{
x = 10; //private data member initialized
cout<<x;
}
};
void main()
{
abc ob; //constructor called
}
Output:
10
Example of parameterized constructor
class abc
{
private:
int x;
public:
abc(int x1)
{
x=x1;
cout<<x;
}
};
void main()
{
abc ob(10);
}
Output: 10.
This is how the use of constructor and that make program more easy to use.
Destructor
A destructor is used to destroy i.e. free up the memory space occupied by the objects of class.
Properties of Destructor
- Destructor has the same name as class name, but it is preceded by tilde (~) sign.
- Destructor releases the memory space occupied by the objects of a class, at the time of program termination.
- Destructor is called automatically, at the time of program termination.
Example of destructor
class abc
{
private:
int x;
public:
abc(int x1) //parameterized constructor
{
x = x1;
cout<<x;
}
~abc() // destructor
{
cout<<”\nDestructor called”;
}
};
void main()
{
abc ob(10); //parameterized constructor called- ob’s x will be set to 10
}// destructor called at program termination
Output:
10
Destructor called
Comments
Post a Comment