· Web viewHere the object p1 is assigned to p2 member by member. It is important to note that...

23
Constructors and destructors Usually, the member functions of class can access the data members directly. There are special member functions that can initialize or de-initialize the member variables. These special member functions are called as constructors and destructors. Constructors When we create an object of a class, we need to allocate memory to the object. However, the allocation of memory does not ensure the initialization of the data members within the object. The member variables within a class cannot be initialized at the time of declaring a class. E.g., the initialization of data members in the following code snippet is invalid: class GreatNumber { int a=10; //wrong int b=20; //wrong }; The problem of not initializing a data member at the time of declaring a class can be overcome by writing an initialization function in a class that assigns initial values to each data member. This initialization function can be invoked when an object is created. This initialization function is called as constructor. Characteristics or properties of a constructor 1. A constructor name must be the same as the class name. 2. A constructor should be declared in public section. 3. A constructor should not return any value (not even void). Constructor is a special member function that is used to initialize data members and that can be invoked automatically whenever an

Transcript of · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that...

Page 1: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

Constructors and destructors

Usually, the member functions of class can access the data members directly. There are special member functions that can initialize or de-initialize the member variables. These special member functions are called as constructors and destructors.

Constructors

When we create an object of a class, we need to allocate memory to the object. However, the allocation of memory does not ensure the initialization of the data members within the object. The member variables within a class cannot be initialized at the time of declaring a class. E.g., the initialization of data members in the following code snippet is invalid:

class GreatNumber

{ int a=10; //wrong

int b=20; //wrong

};

The problem of not initializing a data member at the time of declaring a class can be overcome by writing an initialization function in a class that assigns initial values to each data member. This initialization function can be invoked when an object is created. This initialization function is called as constructor.

Characteristics or properties of a constructor

1. A constructor name must be the same as the class name.2. A constructor should be declared in public section.3. A constructor should not return any value (not even void).4. A constructor can be called automatically. There is no explicit call needed.5. A constructor can take arguments. As it can take arguments, these arguments can have

default values.6. As constructor can take arguments, constructor can be overloaded. 7. A constructor can make implicit calls to the memory management operators new and

delete when the memory allocation is needed.Types of constructors:

Constructor is a special member function that is used to initialize data members and that can be invoked automatically whenever an object is created.

Page 2: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

Default constructor: In C++, a constructor is the first member of a class that is invoked automatically when an object of the class is created. This means that whenever an object of a class is created, the constructor of the class is invoked. However, what would happen when we do not define a constructor in the class? In that case, the C++ compiler creates a constructor for that class. This compiler created constructor is called as the default constructor.

We can create a default constructor in a class by simply adding a constructor without any argument and providing the same name as the class name, in the public section of the class. When we declare an instance (an object) of class, whether we use that object or not, the default constructor of the class is invoked automatically. The following program gives the creation of default constructor:

Write a program to create a default constructor

# include<iostream>using namespace std;class Number{ int x,y,z;

public: Number( )

{ cout<<”\n Default constructor is called”;x=1;y=2;z=3;

}

void display(){ cout<<”\n x=”<<x<<”\t y=”<<y<<”\t z=”<<z;

Constructors

Default Constructor

Parameterized Constructor

Default argument

Constructor

Copy Constructor

Dynamic Constructor

Default constructor is a constructor that has no parameters.

Page 3: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

}};int main(void){ Number ob; //object is created- default constructor gets called.

Ob.display();return 0;

}Output: Default constructor is called

x=1 y=2 z=3

Parameterized constructor: In the default constructor we cannot pass the parameters (or arguments), but in real projects we require to initialize the data members of the objects when they are created. It is also required to initialize the different objects with different values. This is achieved by using a parameterized constructor.

When parameterized constructors are used in the program, it is necessary to pass the appropriate arguments when objects are created. The arguments (parameters) of a constructor can be of any type except that of the class to which it belongs.

In C++, a constructor with arguments can co-exist with another constructor without any argument. In other words, it is possible to have more than one constructor in a class. This concept is called as “constructor overloading”.

When a parameterized constructor is used, the object can be declared in the following two ways:

1. By explicitly calling the parameterized constructor:

In the process of object creation, the constructor name is provided explicitly.

Ex: Sample s=Sample(10,20,53);

Here Sample is a class that has parameterized constructor with three integer arguments.

2. By implicitly calling the parameterized constructor:

A parameterized constructor is a constructor that has arguments.

<class_name> <object_name>= <class_name>(arguments);

<class_name> <object_name>(arguments);

Page 4: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

This is very simple method to initialize the object using the parameterized constructor. Here, the constructor name is not needed.

Ex: Sample s(10,20,53);

Here object s of class Sample is created. Its integer data members can be initialized with given values.

The following program demonstrates this concept of using parameterized constructor:

Write a program to create a parameterized constructor

# include<iostream>using namespace std;class Number{ int x,y,z;

public: Number(int a,int b,int c){ x=a;

y=b;z=c;

}void display(){ cout<<”\n x=”<<x<<”\t y=”<<y<<”\t z=”<<z; }

};int main(void){ Number ob(10,20,40); //object is created- parameterized constructor gets called.

ob.display();return 0;

}Output: x=10 y=20 z=40Note: one argument constructor’s call looks same as the assignment statement.

Ex: #include<iostream>

using namespace std;

class Sample

This constructor’s definition can also be written as:

Numbers::Numbers(int a,int b,int c):x(a),y(b),z(c)

{

}

Page 5: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

{

int x;

public: Sample(int a): x(a) //one-argument constructor

{

}

void print()

{ cout<<”x=”<<x; }

};

int main()

{

Sample s=10;

s.print();

return 0;

}

Default argument constructor:

A constructor can have arguments and each of these arguments can be given a default value. So,

Whenever we want to give default values to arguments, we should keep these things in mind:

The default values should be given from right side argument to left side argument. If we want to give a default value to an argument, make sure that default values are

given to all the arguments that are right to it. If we want to remove a default value from an argument, make sure that all the default

values to its left are removed.The following program demonstrates default argument constructor:

# include<iostream>using namespace std;class Number

A default argument constructor is a parameterized constructor with default values.

Page 6: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

{ int x,y,z;public: Number(int a,int b=3,int c=5){ x=a;

y=b;z=c;

}void display(){ cout<<”\n x=”<<x<<”\t y=”<<y<<”\t z=”<<z; }

};int main(void){ Number ob1(10,20,40),ob2(10,40),ob3(70);

ob1.display();ob2.display();ob3.display();return 0;

}Output: x=10 y=20 z=40

x=10 y=40 z=5 x=70 y=3 z=5Copy Constructor

As we know that it is possible to have a constructor with arguments. We can pass values of any type as parameters to constructor, except an object of its own class. E.g., in this code snippet, the following constructor declaration is invalid:

class Product

{

…….

…….

public: Product(Product obj); //invalid declaration

};

However, a class’s own object can be passed as a reference parameter. Reference parameters are indicated by an ampersand (&) symbol that precedes the argument. For example, in the following code snippet, passing a reference argument of Product class is valid:

Page 7: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

class Product

{

…….

…….

public: Product(Product &obj); //valid declaration: A copy constructor

};

A copy constructor copies the data members from one object to another object. A copy constructor can be defined outside of class as follows:

Ex: Product::Product(Product &p)

{

}

Once the copy constructor is defined, it gets called as follows:

Ex: Product p2=p1;

(or)

Product p2(p1);

Here the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor with arguments. It is because that a source object should be declared before it is used. The declared source object invokes either default constructor or parameterized constructor.

<class_name>:: <class_name>(<class_name> & <object_name>)

{

//statements

}

<class_name> <dest_object>=<Source_object>;

(or)

<class_name> <dest_object>(<Source_object>);

A constructor having a reference to an object of its own class is known as copy constructor.

Page 8: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

Note: Difference between assignment statement that assigns one object to another and copy constructor:

Product p2=p1; //invokes copy constructor

p2=p1; //the compiler copies the data from p1 to p2, member by member, using the = operator.

The following program demonstrates copy constructor:# include<iostream>using namespace std;class Product{ int num; public: Product() { } void getNumber() { cout<<"\n Enter product number"; cin>>num; } Product(Product &p) { num=p.num; } void print() { cout<<num; }};int main(){ Product p1,p3; //invokes default constructor p1.getNumber(); Product p2(p1); //invokes copy constructor p3=p1; cout<<”\n The value in object p1=”; p1.print(); cout<<”\n The value in object p2=”; p2.print(); cout<<”\n The value in object p3=”; p3.print(); return 0;}Output: Enter product number 4343The value in object p1=4343The value in object p2=4343

Dynamic constructor

A constructor that can allocate the required amount of memory to object at the time of their construction or at run time is known as a dynamic constructor.

Page 9: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

The purpose of the constructor is to initialize the data members of an object. The dynamic initialization of object means the initial values may be provided at the runtime. The constructors which allocate memory at runtime are called as dynamic constructors. The new operator is used to allocate memory at run time. One advantage of dynamic initialization is that we can provide various initializations formats using overloaded constructors. The following program demonstrates this concept:

Page 10: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

Output:

Page 11: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

Constructor overloading

In C++, we can overload a constructor in the same way as we overload a function. This means that a class can have different constructors that follow the same rules of overloading, as a function follows. When we declare different constructors with different arguments within a class, make sure that you initialize each instance of the class with the right number of arguments; otherwise, the compiler generates an error. The following program demonstrates this concept:

Write a program to overload a constructor

//program to overload a constructor# include<iostream>using namespace std;class Area{ public: Area(int s) { cout<<”\n Area of square=”<<(s*s); } Area(int l,int b) { cout<<”\n Area of rectangle=”<<(l*b); }

Area(int a,int b,int c) { float s=(a+b+c)/2;

float ans=(s*s-a*s-b*s-c);cout<<”\n Area of triangle=”<<sqrt(ans);

}};int main(){ Area a1(5);

Area a2(4,3);Area a3(1,3,5);

return 0;}Destructors

When the variables of built-in data types are not needed, they are automatically destroyed by the compiler. Similarly, we can destroy the object created by the user-defined data type “class”. To destroy the object, a special member function is used. That special member function is called as a destructor.

The destructor function has the following properties:

Destructor is a special member function that is called automatically whenever an object of the class to which it belongs goes out of existence.

Page 12: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

A destructor name must be the same as of its class name. Its name should be preceded by a tilde symbol (~). It should be declared in public section. It does not take any argument. It does not return any value (not even void). A destructor gets called automatically; no explicit call is needed. It cannot be overloaded. We cannot refer to its addresses. Whenever objects are created, they occupy some memory space. If we do not destroy the

object, the memory will remain allocated to them. Therefore, for the efficient utilization of memory, we must destroy the objects when they are not required. This task is performed by destructor.

The destructors are used for efficient memory utilization. The destructor function releases the memory occupied by the object in the heap. If an object is defined inside the block (local), then the destructor is called when the block gets over and if the object is globally defined, then the destructor is called when the program terminates.

Write a program to demonstrate destructor

//program to demonstrate destructor#include<iostream>using namespace std;class Array{

int *a,n; public: Array(int); ~Array(); void readArray(); void printArray();};Array::Array(int size){

cout<<"\n constructor is called"; n=size; a=new int[n];}Array::~Array()

Page 13: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

{ delete[] a;

cout<<"\n Destructor is called";}void Array::readArray(){

cout<<"\n Enter the array elements:"; for(int i=0;i<n;i++) cin>>a[i];}void Array::printArray(){

cout<<"\n The array elements are:"; for(int i=0;i<n;i++) cout<<a[i]<<"\t";}int main(void){ int size;

cout<<"\n Enter the array size:";cin>>size;Array a(size);a.readArray();a.printArray();return 0;

}Output: Enter the array size: 4

Constructor is calledEnter the array elements: 23 54 5 8The array elements are: 23 54 5 8Destructor is called

Page 14: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

Comparison of constructor and destructor

Constructor DestructorSimilarities

A constructor should be declared in public section of a class.

A destructor should be declared in public section of a class.

A constructor should not return any value (not even void).

A destructor should not return any value (not even void).

A constructor may never be static. A destructor may never be static.We cannot refer to a constructor’s address. We cannot refer to a destructor’s address.An object with a constructor cannot be used as a member of a union.

An object with a destructor cannot be used as a member of a union.

DifferencesA constructor is used to initialize the object. A destructor is used to destroy the object.A constructor name must be the same as the class name.

A destructor name must also be the same as the class name but preceded by ~ sign.

Constructors can be parameterized. Destructor does not take any argument.Constructor is invoked automatically when the object is created.

Destructor is invoked automatically when the object goes out of existence.

Since a constructor can be parameterized, it can be overloaded.

Since destructor does not take any argument, it can never be overloaded.

Since a constructor can be parameterized, it can have default arguments.

Since destructor does not take any argument, it cannot have default arguments.

Friend Functions

The private data members of a class cannot be accessed by any non-member function. The private data members can only be accessed by the member functions of the same class. There are two alternative options by which a non-member function can access the private members: First way is to make the private members of class as public and pass its object to non-member function. The other mechanism for accessing private members is called as friend function.

Properties:

1) A friend function is declared same as a normal function is declared except that the function declaration is preceded by the keyword “friend”.

2) A friend function is declared in any section of the class(es) in which it wants to access private members.

3) A friend function contains object(s) as argument(s) whose private data it wants to access.

Friend function is a special non-member function that can access private members of a class.

Page 15: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

4) As this is not a member function, the scope resolution operator is not used when we want to define a friend function outside of the class.

5) A friend function can never be invoked with the help of an object.6) A friend function can access more than one class’s private members.

Friend function for accessing one class’s private members:

When we want to access private members of a class, we should do the following:

a) Declare the friend function within the class, in any section, in which we want to access private members. In order to access the private members of a class, its object as an argument is needed.

b) Define the friend function outside of the class or inside of the class as we define a normal function. If it is defined inside of the class, it becomes inline. If it is defined outside, there is no need of scope resolution operator.

c) Call the friend function as we call a normal function. In other words, an object is not needed to call a friend function.

The following program demonstrates this concept:

# include<iostream>using namespace std;class Number{ int x,y,z;

public:Number(int a,int b,int c){ x=a;

y=b;z=c;

}friend int sum(Number); //step-a

};int sum(Number ob) //step-b{ int ans;

ans=ob.x+ob.y+ob.z;return ans;

}int main(void){ Numbers ob(10,20,40); //object is created- parameterized constructor gets called.

int ans;

Page 16: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

ans=sum(ob); //step-ccout<<”\n Sum=”<<ans;return 0;

}Output: Sum=70

A common friend function to multiple classes: When we want to create a friend function that is common friend function to multiple classes, we should do these:

1) Forward declaration: Declare all the classes except the first class, in advance before their definitions and before the definition of friend function. This is because when a common friend function to multiple classes is declared, then the first class does not about the second class whose object is passed as an argument.

2) Declare friend function in all classes whose private members it wants to access. Pass the objects of all classes as arguments.

3) Define the friend function outside of all classes as a normal function is defined.4) Call the friend function as a normal function is called.

The following program demonstrates this concept:

# include<iostream>using namespace std;class Second; //step-1 : Forward declarationclass Third;class First{ int x;

public: First(int a) { x=a; }friend int max(First,Second,Third); //step-2

};class Second{ int y;

public: Second(int b) { y=b; }friend int max(First,Second,Third); //step-2

};class Third{ int z;

public: Third(int c){ z=c; }friend int max(First,Second,Third); //step-2

};int max(First f,Second s,Third t) //step-3{ if(f.x>s.y && f.x>t.z)

return f.x;else if(s.y>t.z)

return s.y;else

return t.z;}int main(void)

Page 17: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor

{ First f(10);Second s(20);Third t(45);int ans=max(f,s,t); //step-4cout<<”\n Biggest number=”<<ans;return 0;

}Output: Biggest number=45

Page 18: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor
Page 19: · Web viewHere the object p1 is assigned to p2 member by member. It is important to note that if we declare a copy constructor we must also declare a default constructor or constructor