Saturday, June 28, 2008

Lesson(2) in class constructor with example codes

Sphere: Related Content Constructor Overloading:
===================
As soon as we provide our own constructor, compiler does not provide any implicit default constructor.
Now it is our headache to provide the class constructors with proper argument list and there definitions as well.
e.g.

class Account{
public:
Account(){cout << "this is default constructor"<< "\n";} Account(int n) {cout << "Value is " <<>

the output:

this is default constructor
Value is 15
The name is C++

The above declarations like:
Account();
Account(int n);
Account(const char *name);

are nothing but constructor overloading.

Constructor Overloading:
===================
Like any other function, a constructor can also be overloaded with more than one function. Those functions will have the same name but different types or number of parameters. For overloaded functions the compiler will call the one whose parameters match the arguments used in the function call. In the case of constructors, which are automatically called when an object is created, the one executed is the one that matches the arguments passed on the object declaration.

**Note:
Remember if we don't declare *any* constructor, compiler will assume that class to have default constructor, and program will compile successfully e.g

class Account{
public:

private:
char *_name;

};

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

But the following program won't compile successfully.

class Account{
public:
//Account(){cout << "this is default constructor"<< "\n";}
Account(int n) {cout << "Value is " <<>
};

int main()
{
Account acc1;
Account acc2(15);
return 0;
}
It will show following compilation error:

Borland C++ 5.5.1 for Win32 Copyright (c) 1993, 2000 Borland
Prac\const_1.cpp:
Error E2285 Prac\const_1.cpp 19: Could not find a match for 'Account::Account()' in function main()
Warning W8004 Prac\const_1.cpp 23: 'acc1' is assigned a value that is never used in function main()
*** 1 errors in Compile ***

reason is we have already provided a constructor for the class, so compiler has stopped providing or assuming that class to have any default constructor. Now no more default constructor. Programmer needs to provide the constructor explicitly.

By the way,
Account acc1() implies a function acc1() which is returning Account. Please don't be confuse this with constructor declaration.
Account acc1(); //wrong
Account acc1; //right




No comments: