Constructors and Destructors.
Instructor Jeff Zhuk
|
When you create an object, you may want to initialize some of
the attributes.
Automatic initialization is carried out using a special method
called a constructor.
A constructor is declared using the class name as the method name.
Using the Employee class from a previous example,
the constructor would be:
|
// C++ constructor example
Employee::Employee(char* myName,
int salary)
{
strncpy(name, myName);
wage=salary;
}
|
// Java Constructor example
public Employee(String myName,
int salary)
{
name = myName;
wage = salary;
}
|
This would allow you to initialize both the name and the salary
with data passed from the calling during the object declaration:
Employee bob("Bob Smith",2000);
which would initialize the name to Bob Smith and his salary to $2000.00 .
The attributes of an object do not need to be passed to the object
for the constructor to work. The constructor could be
// C++ Example
Employee::Employee( )
{
wage = 2000;
}
|
// Java Example
public Employee()
{
wage = 2000;
}
|
which would initialize just the salary of person being constructed.
 |
C++ also offers a destructor function that is automatically executed
when the object is deleted.
The destructor has the same name as the constructor
(which is the same as the class name), but preceded by a tilde.
The destructor for the person class would be:
|
Employee::~Employee( ) { };
Java has its own internal garbage collection mechanism.
Java programmers are free from this boring task to deallocate memory space.
Back to Object Oriented Concepts