Types of Constructors
5A. Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters.
// Cpp program to illustrate the
// concept of Constructors
#include <iostream.h>
class
construct
{
public
:
int
a, b;
// Default Constructor
construct()
{
a = 10;
b = 20;
}
};
voidmain()
{
// Default constructor called automatically
// when the object is created
construct c;
cout <<
"a: "
<< c.a << endl <<
"b: "
<< c.b;
}
Output:
a: 10 b: 20
5B. Parameterized Constructors: 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.
// CPP program to illustrate
// parameterized constructors
#include<iostream.h>
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;
}
};
voidmain()
{
// Constructor called
Point p1(10, 15);
// Access values assigned by constructor
cout <<
"p1.x = "
<< p1.getX() <<
", p1.y = "
<< p1.getY();
}
output:p1.x = 10, p1.y = 15
Paramaterized Constructor video: 5minuteshttps://www.youtube.com/watch?v=2LxU7vroRj0
No comments:
Post a Comment