Constructors and Destructors.

Constructor
A constructor is a special method of a class or structure in object-oriented programming that initializes an object of that type. A constructor is an instance method that usually has the same name as the class, and can be used to set the values of the members of an object, either to default or to user-defined values.
Constructors are not called explicitly and are invoked only once during their lifetime. In the case of a hierarchy of classes where a derived class inherits from a parent class, the execution sequence of the constructor is a call to the constructor of the parent class first and then that of the derived class. Constructors cannot be inherited.
A constructor can be declared using any of the access modifiers. It is mandatory to have a constructor with the right access modifier. However, the compiler supplies a default if an access modifier is not defined in the class. If a constructor is declared as private, the class cannot be created or derived and hence cannot be instantiated. Such a constructor, however, can be overloaded with different sets of parameters.
* Logic involving specific operations that need to be executed at a particular event in an application - such as opening a database connection - should not be written in a constructor.
The constructor functions have some specia characteristics:- * They should be declared in the public section. * They ae invoked automatically when the objects are created. * They do not have return types, not even void and threfore and they cannot return values. * They cannot be inherited, through a derived class can call the base class constructor. * Like other C++ functions, they can have default arguments. * Constructors cannot be virtual. * We cannot refer to their address. * An object with a constructor (or destructor) cannot be used as a member of a union. * They make 'implicit calls' to the operators new and delete when memory allocation is requried. * When using derived class constructors, the parent class constructor should be passed the correct parameters.
* Better code maintainability comes from having the initialization and other related logic in one main constructor and cross-calling this constructor from other overloaded constructors.
* Because a constructor cannot return a value to the calling code, it is a good practice to throw an exception when a failure is encountered.
* Never Use Virtual Methods in Constructors or Destructors
The various types of Constructor are as follows:-
1. Default Constructor
2. Parameterized Constructor
3.Copy Constructor
Default Constructor
Default Constructor:- Default Constructor is also called as Empty Constructor which has no arguments and It is Automatically called when we creates the object of class but Remember name of Constructor is same as name of class and Constructor never declared with the help of Return Type. Means we cant Declare a Constructor with the help of void Return Type. , if we never Pass or Declare any Arguments then this called as the Copy Constructors.
Example: -
#include < iostream.h >
class Defal
{
public:
int x;
int y;
Defal(){x=y=3;}
};
int main()
{
Defal A;
cout << "Default constructs x,y value::"< return 0;
}
Output: -
Default constructs x,y value:: 3,3
Parameterized Constructor
Parameterized Constructor :- This is Another type Constructor which has some Arguments and same name as class name but it uses some Arguments So For this We have to create object of Class by passing some Arguments at the time of creating object with the name of class. When we pass some Arguments to the Constructor then this will automatically pass the Arguments to the Constructor and the values will retrieve by the Respective Data Members of the Class.
#include < iostream.h >
using namespace std;
class Line
{
public:
void setLength( double len );
double getLength( void );
Line(double len);
private:
double length;
};
Line::Line( double len)
{
cout << "Object is being created, length = " << len << endl;
length = len;
}
void Line::setLength( double len )
{
length = len;
}
double Line::getLength( void )
{
return length;
}
int main( )
{
Line line(10.0);
cout << "Length of line : " << line.getLength() < line.setLength(6.0);
cout << "Length of line : " << line.getLength() < return 0;
}
Output: -
Object is being created, length = 10
Length of line : 10
Length of line : 6
Copy Constructor
Copy Constructor :- This is also Another type of Constructor. In this Constructor we pass the object of class into the Another Object of Same Class. As name Suggests you Copy, means Copy the values of one Object into the another Object of Class .This is used for Copying the values of class object into an another object of class So we call them as Copy Constructor and For Copying the values We have to pass the name of object whose values we wants to Copying and When we are using or passing an Object to a Constructor then we must have to use the & Ampersand or Address Operator.
The copy constructor is used to:-
* Initialize one object from another of the same type.
* Copy an object to pass it as an argument to a function.
* Copy an object to return it from a function.
If a copy constructor is not defined in a class, the compiler itself defines one.If the class has pointer variables and has some dynamic memory allocations, then it is a must to have a copy constructor. The most common form of copy constructor is shown here:-
#include < iostream >
using namespace std;
struct A {
int i;
A() : i(10) { }
};
struct B {
int j;
B() : j(20) {
cout << "Constructor B(), j = " << j << endl;
}
B(B& arg) : j(arg.j) {
cout << "Copy constructor B(B&), j = " << j << endl;
}
B(const B&, int val = 30) : j(val) {
cout << "Copy constructor B(const B&, int), j = " << j << endl;
}
};
struct C {
C() { }
C(C&) { }
};
int main() {
A a;
A a1(a);
B b;
const B b_const;
B b1(b);
B b2(b_const);
const C c_const;
}
Output:-
Constructor B(), j = 20
Constructor B(), j = 20
Copy constructor B(B&), j = 20
Copy constructor B(const B&, int), j = 30
Destructor
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.
A destructor is a member function with the same name as its class prefixed by a ~ (tilde). For example:
class X {
public:
// Constructor for class X
X();
// Destructor for class X
~X();
};
A destructor takes no arguments and has no return type. Its address cannot be taken. Destructors cannot be declared const, volatile, const volatile or static. A destructor can be declared virtual or pure virtual.
If no user-defined destructor exists for a class and one is needed, the compiler implicitly declares a destructor. This implicitly declared destructor is an inline public member of its class.
The compiler will implicitly define an implicitly declared destructor when the compiler uses the destructor to destroy an object of the destructor's class type. Suppose a class A has an implicitly declared destructor. The following is equivalent to the function the compiler would implicitly define for A:
A::~A() { }
The compiler first implicitly defines the implicitly declared destructors of the base classes and nonstatic data members of a class A before defining the implicitly declared destructor of A
A destructor of a class A is trivial if all the following are true:
* It is implicitly defined
* All the direct base classes of A have trivial destructors
* The classes of all the nonstatic data members of A have trivial destructors
If any of the above are false, then the destructor is nontrivial.
A union member cannot be of a class type that has a nontrivial destructor.
Class members that are class types can have their own destructors. Both base and derived classes can have destructors, although destructors are not inherited. If a base class A or a member of A has a destructor, and a class derived from A does not declare a destructor, a default destructor is generated.
The default destructor calls the destructors of the base class and members of the derived class.
The destructors of base classes and members are called in the reverse order of the completion of their constructor:
* The destructor for a class object is called before destructors for members and bases are called.
* Destructors for nonstatic members are called before destructors for base classes are called.
* Destructors for nonvirtual base classes are called before destructors for virtual base classes are called.
When an exception is thrown for a class object with a destructor, the destructor for the temporary object thrown is not called until control passes out of the catch block.
Destructors are implicitly called when an automatic object (a local object that has been declared auto or register, or not declared as static or extern) or temporary object passes out of scope. They are implicitly called at program termination for constructed external and static objects. Destructors are invoked when you use the delete operator for objects created with the new operator.
Example: -
#include < iostream.h >
int cnt=0;
class display
{
public:
display()
{
cnt++;
cout << "\nCreate Object::" << cnt;
}
~display()
{
cout << "\nDestroyed Object::" << cnt;
cnt--;
}
};
int main()
{
cout << "\nMain Objects x,y,z\n";
display x,y,z;
{
cout << "\n\nNew object 4\n";
display B;
}
cout << "\n\nDestroy All objects x,y,z\n";
return 0;
}
Result:
Main Objects x,y,z
Create Object::1
Create Object::2
Create Object::3
New objects 4
Create Object::4
Destroyed Object::4
Destroy All objects x,y,z
Destroyed Object::3
Destroyed Object::2
Destroyed Object::1
In the above example both a constructor "display()", destructor "~display()" is used. First three objects x,y,z are created, then a fourth object is created inside "{}". The fourth object is destroyed implicitly when the code execution goes out of scope defined by braces. Finally all the exisiting objects are destroyed.


Free Web Hosting