What is Constructor in C++ with examples?
In this chapter of C++ interview questions, we will learn about:
-
what is constructor in c++?
-
syntax of constructor in c++
-
example of constructor in c++
What is Constructor in C++?
-
Constructor is a 'special' member function, which is used for initialization of all objects.
-
Why constructor is 'special'? - because the class name and constructor name is same.
-
Compiler calls it when an object is created.
-
It initialize values after storage allocation of object.
Syntax of constructor in C++
Given below is example depicting syntax of constructor in c++:
class Rectangle
{
double length,breadth;
public:
Rectangle(void); // constructor called
};
Rectangle :: Rectangle(void) // constructor defined
{
length=0;
breadth=0;
}
Example of constructor in c++
Given below is an example of constructor in c++:
#include <iostream>
using namespace std;
class Rectangle
{
public:
double sarea(double length, double breadth);
double garea(void); Rectangle(void); // Constructor Created
private: double a;
};
Rectangle::Rectangle(void) // definition of Constructor
{
cout<<"Object is here"; cout<<endl;
}
// defining other functions
double Rectangle::sarea(double length, double breadth)
{ a=length*breadth; }
double Rectangle::garea(void)
{
return a;
}
int main()
{
Rectangle R;
R.sarea(10.0,12.0);
cout<<"Area of Rectangle"<<" "<<R.garea();
cout<<endl;
return 0;
}
Output
Object is here
Area of Rectangle 120.0
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Page Views :
Published Date :
Feb 04,2021