Friday, June 27, 2008

Lesson(1) in class constructor with example codes

Sphere: Related Content Default Constructor:
===============
If no constructor is declared in the class definition then compiler assumes class to have default constructors without any arguments.
e.g.

class Account
{

public:
private:
char *_name;

unsigned int _acct_num;
double _balance;
};

int main()
{
Account acc;
return 0;
}


The above program will compile successfully. Though there is no class constructor. In this case compiler will assume that Account class has default constructor. So we can declare a object of this class by simply declaring object without any arguments. like
Account acc;

Eventually we can write our own default constructor
e.g.

class Account{
public:
Account() {cout << "this is default constructor"<<>
private:
char *_name;
unsigned int _acct_num;
double _balance;
};

int main()
{
Account acc;
return 0;
}



Now output of the program is :
this is default constructor

So in this way we can provide our own default constructor.

No comments: