Que- what is constructor? Explain it?
Ans- Constructor are special type of member function of class which is same name as class. And it is automatically call on the time of object declaration.
Types of Constructor:-
- Default constructor
- Parameterized constructor
- Copy constructor
Default constructor:-
A default constructor is that which has no parameters and inside the scope of default constructor we set the data , values, etc. Which is automatically call on the time of object declaration.
Parameterized constructor:-
Parameterized constructor is that Constructor in which we pass the parameters. It is possible to pass arguments to constructors. Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object.
Copy constructor:-
A copy constructor is a member function which initializes an object using another object of the same class. Detailed article on Copy Constructor. Whenever we define one or more non-default constructors( with parameters ) for a class, a default constructor( without parameters ) should also be explicitly defined as the compiler will not provide a default constructor in this case. However, it is not necessary but it’s considered to be the best practice to always define a default constructor.
Example of default constructor:-
#include<iostream>
using namespace std;
class krishna
{
int radius;
float area,pi;
public:
krishna ()
{
pi=3.14;
}
void getdata ()
{
cout<<"enter radius of circle :-";
cin>>radius ;
area=pi*radius*radius ;
cout<<"area of circle is:-"<<area;
}
};
int main()
{
krishna ob ;
ob. getdata ();
return 0;
}