Professional Documents
Culture Documents
Chapter 6
6.1 Introduction
Constructors and destructors are member
functions of any class.
They are automatically called when a
class object is created or destroyed,
respectively.
6.2 Constructor functions
The constructor function is executed when
a class object is defined.
It can be argumentless or with arguments.
It should have the following:
No return data type,
The same name as the class name,
An optional initialization list may follow the
name and arguments of the constructor,
Public declaration within the class.
Example:
// name.h
class name
{
private:
variable declarations
public:
name(); // constructor
};
// name.cpp
name::name(arguments):initialization list
{
statements
}
Example:
//declaration within a class account
class account {
public:
account();
};
atm Atm1,Atm2;
Atm1=Atm2;
}
// atm.h
class atm {
public:
};
// atm.cpp
atm atm::operator=(const atm& SourceAtm) {
if (this == &SourceAtm)
return (*this);
if (NumAccounts != SourceAtm.NumAccounts) {
cout "Error in assignment: different array sizes.\n";
return 0;
}
else {
EnteredCode = SourceAtm.EnteredCode;
CardCode = SourceAtm.CardCode;
for (int i = 0; i < NumAccounts; i++)
Account[i] = SourceAtm.Account[i];
return (*this);
}
}