Constructors and destructors
A constructor is a method whose name is the same as the class to
which it belongs
The aim of a constructor is to build and objects belonging to a
class. This means initializing the attributes and (frequently)
memory allocation on the heap
A constructor with an empty arguments list (or with just default
arguments) is called the default constructor
3.
Constructors and
destructors
class integer
{
intm,n;
public:
integer(void); // constructor declared
……………..
……………..
};
// class with a constructor
integer :: integer(void)
{
m=0; n=0; // constructor defined
}
integer int1; // object int1 created
4.
Constructors and
destructors
The constructorfunctions have some special characteristics.
These are:
They should be declared in the public section.
They are invoked automatically when the objects are
created.
They do not have return types, not even void and
therefore, and they cannot return values.
Like other C++ functions, they can have default
arguments
They make ‘implicit calls’ to the operators new and
delete when memory allocation is required.
Constructors and
destructors
ParameterizedConstructors
•By calling the constructor explicitly
•By calling the constructor implicitly
integer int1 = integer(0,100); //explicit call
integer int1(0,100); // implicit call
7.
Constructors and
destructors
Aconstructor whose only argument is a reference to an object of the
same kind is called copy constructor
The copy constructor is normally used
when an object is initialized by assignment
when an object is passed by value to a function
If a copy constructor is not provided explicitly by the user, the
compiler will provide a default one
8.
Constructors and
destructors
A destructoris a method with the same name as the class’
preceded by a ~
The destructor is automatically invoked when an object is
destroyed (either because delete has been invoked or because the
object went out of scope
The destructor task is to make sure that the object on which it is
operating will be destroyed without any consequence. In particular,
if any memory has been allocated (in the constructor) the
destructor must return it to the heap