What is Constructor in C++ with examples?

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;

Rectangle(void); // constructor called

Rectangle :: Rectangle(void) // constructor defined

Example of constructor in c++

Given below is an example of constructor in c++:

#include <iostream> 
using namespace std; 

class Rectangle 
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;
 cout<<"Area of Rectangle"<<" "<<R.garea();

return 0; 


Object is here

 Area of Rectangle 120.0


cpp interview questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by

About the Author
Subhajit Guha Thakurta
Page Views :    Published Date : Feb 04,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!