C++ parameter constructor
The constructor integer(), defined above initializes the data members of all the objects to zero. whenever in practice it may be necessary to initialize. The various data elements of different objects with different values when they are create. c++ language permits us to achieve this objective by passing arguments to the constructor function when the objects are created. The constructors that take arguments are known
parameterized constructor
The constructor integer() may be modified to take arguments show below
class integer
{
m,n;
:
integer( x, y);
……….
……….
};
integer::integer(int x,int y)
{
m=x;
n=y;
}
|
when a constructor has been parameterized, the object declaration of integer class statement such as integer int1;
may not be work. we have to pass the initial values as arguments to the constructor when an object is declared.
This can be done in 2 types
1. by calling the constructor explicitly
2. by calling the constructor implicitly
The following declaration illustrates the first method
integer int1=integer(0,100);
|
This statement creates an integer object int1 and passes the values zero (0) and 100(Hundred) to it. The second is implemented as follows
This method, sometimes called the shorthand method is used very often as it is shorter looks better and is easy to implement
Remember , when the constructor is parameterized, we must provide appropriate arguments for the constructor.
Class with CONSTRCUTOR
<iostream>
using namespace std;
class integer
{
m,n;
:
integer(,);
display()
{
cout <<"m="<<m<<"\n";
cout <<"n="<<n<<"\n";
}
};
integer:: integer( x, y)
{
m=x;
n=y;
}
main()
{
integer int1(0,100);
integer int2=integer(25,75);
std::cout<<"\n object1" << "\n";
int1.display();
std::cout<< "\n object2" << "\n";
int2.display();
0;
}
|
output:
object1
m=0
n=100
object2
m=25
n=75
|
The constructor function can also be defined as inline functions examples
class integer
{
m,n;
:
integer( x, y)
{
m=x;
y=n;
}
…….
…….
};
|
The paramters of a constructor can be any type except that of the class to which it belongs to for example
class A
{
……
……
:
A(A);
};
|
Thus the statement
is illegal
because however, a constructor can accept a reference to its own class as a parameter.
Class All
{
……
……
A(A&);
};
|
is valid in such cases the constructor is called the copy constructor