CONSTRUCTORS & DESTRUCTORS

advertisement
Constructors
and
destructors
c
constructors
A constructor is a special member function whose task is to
initialize the objects of its class.
Class integer
{
Int m,n;
Public:
Integer(void);
…………
………..
};
Integer::integer(void)
{
m=0;n=0;
}
Parameterized
constructors
The constructors that can take arguments are called parameterized
constructors.
Class integer
{
int m,n;
public:
Integer(int x,int y);
……
……
};
Integer::integer(int x, int y)
{
m=x;n=y;
}
Multiple constructors in a
class
In the first case,the constrector it self supplies the date
values and no values are passed by the calling program.
In the second case,the function call passes the appropriate
values from main().
Class int
{
int m,n;
public:
Int() {m=0; n=0;}
int(int a, int b)
{m=a;n=b;}
Int(int & i)
{m=I; n=I,n;}
};
Constructors with default arguments
• The actual parameter,when specified,overrides the
default value
Dynamic initialization of objects
• This provieds the flexibility of using different format of
date at run time depending upon the situasion
Copy constructor
• A copy constructor is used to declare and initialize an
object from another object
•
Integer (integer &i);
Download