CONSTRUCTORS (1)
CONSTRUCTORS (1)
Session Objectives
Upon completing this session you should be
able to:
Differentiate constructor and destructor
List characteristics of constructor and destructor
Use constructors and destructors
Constructors
been declared
It is called automatically
cannot be referenced
Declaration of Constructors
A constructor is declared and defined as follows:
int main() {
MyClass myObj; // Create an object of MyClass (this will call the constructor)
return 0;
}
Example
class Rectangle
{
private:
int length;
int width;
...
public:
Rectangle(int l, int w); //declaration of constructor
...
};
//definition of constructor
Rectangle::Rectangle(int l, int w)
{
length=l;
width=w;}
Calling Constructors
Parameterized constructors are constructors that are passed arguments when they are called. Unlike
default constructors, parameterized constructors are not created automatically by the compiler if they
are not defined in a class. And these constructors must be defined. For example:
class Rectangle
{
private: int length;
int width;
...
public:
Rectangle(int l, int w);
...
};
//definition of a parameterized constructor
Rectangle::Rectangle(int l, int w)
{ length=l; width=w; }
There are two ways of passing arguments to parameterized constructors when they are called: by
calling the constructor explicitly and by calling the constructor implicitly. For example Rectangle
rect1= Rectangle( 6, 5); //explicit call Rectangle rect1(6, 5); //implicit call Implicit call is the one that
is normally used.
c) Copy constructors
return 0;
}
Destructors
}
Example
Rectangle::~Rectangle()
{
cout<< “An object has been destroyed”<<endl;
}
Note that just like other member functions, constructors can have
default arguments and they can be overloaded.
Example
#include<iostream>
using namespace std;
class Test
{
public:
Test()
{
cout<<"\n Constructor executed";
}
~Test()
{
out<<"\n Destructor executed";
}
};
main()
{
Test t;
return 0;
}
Revision Questions