Constructor and Destructor in C or C++ Programming - learnit

Home Top Ad

Post Top Ad

Wednesday, January 5, 2022

Constructor and Destructor in C or C++ Programming

Constructor and Destructor in C or C++ Programming

Constructor

A constructor is a class member function with the same name as the class. It aids in the initialization of a class's object. It can either accept or reject the arguments. It is used to allocate memory to a class's object. When a new instance of the class is created, it is called. It can be defined either manually or automatically, with or without arguments. A class can have multiple constructors. It can be overloaded, but not inherited or virtualized. A copy constructor is a concept that is used to initialize an object from another object.


Syntax:

ClassName()
{
//Constructor's Body
}

Example

class myclass{
public:
myclass(){
int a,b,total;
cout<<"Please input Number A";
cin>>a;
cout<<"Please input Number B";
cin>>b;
total=a+b;
total<<"Total="<<"\t" <<total;
} };


Destructor

Destructor, like constructor, is a member function of a class with the same name as the class name preceded by a tilde( ) operator. It aids in the de-allocation of an object's memory. It is called when the class's object is freed or deleted. A class always has a single destructor with no parameters, so it cannot be overloaded. It is always invoked in the opposite order as the constructor. If a class is inherited by another class and both classes have a destructor, the child class's destructor is called first, followed by the parent or base class's destructor.

Syntax:

~ClassName()
{
//Destuctor's Body
}


Example

class myclass{
public:
~myclass(){
cout<<"Successfully";
}
};

Please Watching My Video is Below

No comments:

Post a Comment

Post Top Ad