In: Computer Science
C++:
1.When and in what order are constructors and destructors called?
2. Create a class without any constructors, and show that you can create objects with the default constructor. Now create a non-default constructor (one with an argument, aka parameterized constructor) for the class, and try compiling again. Explain what happened.
Question 1:
Constructors are called in the order in which they are inherited, and for destructors it is reverse.
For example see this program:
#include <iostream>
using namespace std;
class A
{
public:
//Making constructor of base class
A()
{
cout << "Base constuctor called\n";
}
//Making destructor of base class
~A()
{
cout << "Base destructor called\n";
}
};
class B : public A
{
public:
//Making constructor of derived class
B()
{
cout << "Derived constructor called\n";
}
//Making destructor of derived class
~B()
{
cout << "Derived destructor called\n";
}
};
int main()
{
B ob;
return 0;
}
OUTPUT:
Question 2:
Here is a class without any constructors (ie default), it runs fine.
#include <iostream>
using namespace std;
//Making the class
class Box
{
int l, b;
public:
//Function to show area
void showarea()
{
l = 10;
b = 20;
cout << "Area of the box is :" << l * b << "\n";
}
};
int main()
{
Box ob;
ob.showarea();
return 0;
}
Here is the output of above code:
If we make a parametried constructor then we have to give the parameters while making the object of the class, otherwise it will give error. See this code for example:
#include <iostream>
using namespace std;
class Box
{
int l, b;
public:
Box(int aa, int bb)
{
l = aa;
b = bb;
}
void showarea()
{
cout << "Area of the box is :" << l * b << "\n";
}
};
int main()
{
// Box ob; //This line will cause error
//To fix the error uncomment the below line and comment the above line
Box ob(50, 60);
ob.showarea();
return 0;
}
OUTPUT: