What is a constructor?The main use of constructors is to initialize objects. The function of initialization is automatically carried out by the use of a special member function called a constructor.
Syntax:
Code:
<class name> { arguments};
What is copy Constructor?This constructor takes one argument. Also called one argument constructor. The main use of copy constructor is to initialize the objects while in creation, also used to copy an object. The copy constructor allows the programmer to create a new object from an existing one by initialization.
For example to invoke a copy constructor the programmer writes:
Code:
Exforsys e3(e2);
or
Exforsys e3=e2;
Example:
Code:
#include <iostream.h>
class Exforsys
{
private:
int a;
public:
Exforsys()
{ }
Exforsys(int w)
{
a=w;
}
Exforsys(Exforsys& e)
{
a=e.a;
cout<<” Example of Copy Constructor”;
}
void result()
{
cout<< a;
}
};
void main()
{
Exforsys e1(50);
Exforsys e3(e1);
cout<< “ne3=”;e3.result();
}
In the above the copy constructor takes one argument an object of type Exforsys which is passed by reference. The output of the above program is
Code:
Example of Copy Constructor
e3=50
Important things about constructors:
1. A constructor takes the same name as the class name.
2. The programmer cannot declare a constructor as virtual or static, nor can the programmer declare a constructor as const, volatile, or const volatile.
3. No return type is specified for a constructor.
4. The constructor must be defined in the public. The constructor must be a public member.
5. Overloading of constructors is possible. This will be explained in later sections of this tutorial.
What is assignment operator?So, = is the assignment operator.
Rule:The operand at the right always shifts to left operand.
What is member initialization list?
In C++, whenever an object of a class is created, its constructor is called. But that's not all--its parent class constructor is called, as are the constructors for all objects that belong to the class. By default, the constructors invoked are the default ("no-argument") constructors. Moreover, all of these constructors are called before the class's own constructor is called.
Initialization lists or "initialization lists" are executed at the very beginning of the construction of an object, before the body of the constructor is entered. They are used to initialize the values in the object. The occasions where initialization lists cannot be used is in the initialization of arrays as data members. If you have constants or references in your class, they can only be initialized in the initialization list. So, initialization of members is must in this case.
Code:
class example
{
const int MAX_SIZE;
int& ref;
public:
example(int& r):MAX_SIZE(128), ref(r) {}
// this is wrong
// example() {MAX_SIZE = 128; ref = r; }
};
The objects are initialized in the order they are declared in the class.
I hope this will help you alot.....