DEFINITION 6: CONSTRUCTOR - PRATMG/2143-OOP-Tamang GitHub Wiki
A constructor is a type of class member function that initializes class objects. Constructor is automatically called in C++ when an object (instance of a class) is created. Because it has no return type, it is a special member function of the class.
A constructor is different from normal functions in following ways:
- Constructor has same name as the class itself
- Constructors don’t have return type
- A constructor is automatically called when an object is created.
- It must be placed in public section of class.
- If we do not specify a constructor, C++ compiler generates a default constructor for object (expects no parameters and has an empty body).
// CPP program to illustrate
// parameterized constructors
#include <iostream>
using namespace std;
class Point
{
private:
int x, y;
public:
// Parameterized Constructor
Point(int x1, int y1)
{
x = x1;
y = y1;
}
int getX()
{
return x;
}
int getY()
{
return y;
}
};
int main()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY();
return 0;
}
REFERENCE: