In: Computer Science
In C++ a class can have multiple constructors, but only one destructor. Explain why this is the case using code to highlight why.
Do give thumbs up if you find this answer useful !!!!!!!!!!!!!!!!!!!!!!!!!
Happy learning !!!!!!!!!!!!!!!!!!
CONSTRUCTOR:
SYNTAX:
classname()
{
//constructor's body
}
DESTRUCTOR:
SYNTAX:
~classname()
{
//destructor's body
}
REASON:
NOTE:
Example: you have an apple and an orange ( multiple constructor ) but you need only one knife to cut it where you will never use two knives to cut two fruits.
PROGRAM:
class A
{
//constructor
A()
{
cout<<"constructor called";
}
//constructor1
A(int)
{
cout<< " constructor1 called";
}
//destructor
~A()
{
cout<< " destructor called";
}
};
int main ()
{
A obj1; // constructor called
int obj2;
A obj2; //constructor1 called
} // object gets out of scope so destructor will be called for both objects.
OUTPUT:
constructor called
constructor1 called
destructor called
destructor called