Default Constructor
Default Constructor
Default constructor is the constructor that can be called with no arguments but can have
default arguments.
These are further divided into following parts :
- Default constructor by the compiler.
-Default constructor (provided by the programmer).
-Default constructor with default arguments( provided by programmer).
-Default constructor by the compiler :
When the user doesn't provide any constructor, then the compiler automatically supplies
a default constructor having no arguments.
Example :
#include <iostream.h>
#include <conio.h>
class Account
{
private:
int account_no;
public :
void read()
{
account_no=10;
}
void display()
{
cout<< "Account number is : "<< account_no;
}
};
void main()
{
clrscr();
class Account acc;
acc.read();
acc.display();
getch();
}
Output :
-Default constructor (provided by the programmer) :
The programmer can also specify the default constructor without any parameters.
Example :
#include <iostream.h>
#include <conio.h>
class Account
{
private:
int account_no;
public :
Account()
{
account_no=10;
}
void display()
{
cout<< "Account number is : "<< account_no;
}
};
void main()
{
clrscr();
class Account acc;
acc.display();
getch();
}
Output :
-Default constructor with default arguments( provided by programmer) :
In this, the programmer provides atleast one default parameter to the constructor.
Example :
#include <iostream.h>
#include <conio.h>
class Account
{
private:
int account_no;
public :
Account(int x=10)//default constructor with argument
{
account_no=x;
}
void display()
{
cout<< "Account number is : "<< account_no;
}
};
void main()
{
clrscr();
class Account acc;
acc.display();
getch();
}
Output :
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment