Module_3_Contructors Destructors and Inheritance_Lecture Notes
Module_3_Contructors Destructors and Inheritance_Lecture Notes
CONSTRUCTORS
A constructor is a special member function whose task is to initialize the objects of its class. Constructor is
invoked whenever an object of its associated class is created.
Example:
// class with a constructor
Class integer
{
int m, n;
public:
integer(void); // constructor declared
………
………
};
Rules/Characteristics of constructor
1. They should be declared in the public section.
2. They are invoked automatically when the objects are created.
3. They do not have return types, not even void therefore and they cannot return values.
4. They cannot be inherited, though a derived class can call the base class constructor.
5. They can have default arguments.
6. Constructors cannot be virtual.
7. We cannot refer to constructor addresses.
8. An object with a constructor cannot be used as s member of a union.
9. They make implicit calls to the operators new and delete when memory allocation is required.
Types of Constructors
1. Default Constructors
2. Parameterized Constructors
3. Copy Constructors
Default Constructors
A constructor that accepts no parameters is called default constructor. If default constructors are not defined
compiler supplies a default constructor.
Class integer
{
int m, n;
public:
Reshma, Dept of CSE
MODULE 3: Constructors, Destructors and Inheritance
integer(); // constructor declared
};
Parametrized Constructors
The constructors that can take arguments are called as parameterized constructors. These constructors are used to
initialize the various data elements of different objects with different values when they are created.
Example:
class integer
{
int m, n;
public:
integer(int x, int y); //parameterized constructor
………
………
};
integer :: integer(int x, int y)
{
m=x;
n=y;
}
Copy Constructors
A copy constructor is a member function that initializes an object using another object of the same class. In
simple terms, a constructor which creates an object by initializing it with an object of the same class, which has
been created previously is known as a copy constructor.
Copy constructor is used to initialize the members of a newly created object by copying the members of an
already existing object. Copy constructor takes a reference to an object of the same class as an argument.
Example:
Sample(Sample &t)
{
id=t.id;
}
The process of initializing members of an object through a copy constructor is known as copy initialization.
Reshma, Dept of CSE
MODULE 3: Constructors, Destructors and Inheritance
#include <iostream>
using namespace std;
class Sample {
int id;
public:
void init(int x) { id = x; }
void display() { cout << endl << "ID=" << id; }
};
int main()
{
Sample obj1;
obj1.init(10);
obj1.display();
int main( )
{
integer int1(0,100); //constructor called implicitly
integer int2 = integer(25,75); //constructor called explicitly
cout<<”\NObject1”<<”\n”;
int1.display();
cout<<”\NObject2”<<”\n”;
int2.display();
Reshma, Dept of CSE
MODULE 3: Constructors, Destructors and Inheritance
return 0;
}
OUTPUT
Object1
m=0
n=100
Object2
m=25
n=75
DESTRUCTORS
Destructors are used to destroy the objects that have been created by a constructor. Destructor is a member
function whose name is same as that of class name but it is preceded by a tilde.
Example:
~ integer( ) { }
A destructor never takes any argument nor does it return any value. It will be invoked implicitly by the compiler
upon exit from the program to clean up the storage that is no longer accessible.
Whenever new is used to allocate memory in the constructors, we should use delete to free that memory.
Program to implement Destructor
#include<iostream>
using namespace std;
int count=0;
class alpha
{
public:
alpha()
{
count++;
cout<<”\nNo of object created ”<<count;
}
~alpha()
{
cout<<”\nNo of object destroyed ”<<count;
count--;
Reshma, Dept of CSE
MODULE 3: Constructors, Destructors and Inheritance
}
};
int main( )
{
cout<<”\nEnter main\n”;
alpha A1, A2,A3, A4;
{
cout<<”\nEnter block1\n”;
alpha A5;
}
{
cout<<”\nEnter block2\n”;
alpha A6;
}
cout<<”\nRe-enter main\n”;
return 0;
}
Output:
Enter main
No of object created 1
No of object created 2
No of object created 3
No of object created 4
Enter block1
No of object created 5
No of object destroyed 5
Enter block2
No of object created 6
No of object destroyed 6
Re-enter main
No of object destroyed 4
No of object destroyed 3
No of object destroyed 2
No of object destroyed 1
INHERITANCE
The mechanism of deriving a new class from an old one is called inheritance. The old class is referred to as base
class and the new one is called the derived class or subclass. The derived class inherits some or all of the traits
from the base class.
Types of inheritance
Single inheritance: A derived class with only one base class.
Multiple inheritance: A derived class with several base classes.
Multilevel inheritance: The mechanism of deriving a class from another derived class.
Hierarchical inheritance: The traits of one class being inherited by more than one class.
Reshma, Dept of CSE
MODULE 3: Constructors, Destructors and Inheritance
Hybrid inheritance: Combination of hierarchical and multiple inheritance.
d.b = 20;
d.mul ( );
d.display ( );
return 0;
}
Output:
a=5
a=5
b=10
c=50
a=5
b=20
c=100
The class D is publicly derived from base class B. D inherits all the public members of B, so public members of
the base class B is also a public member of the derived class D. The private members of B cannot be inherited by
D. The class D will contain following members as shown
d.mul ( );
d.display ( );
return 0;
}
Output:
Enter values for a and b: 5 10
a=5
b=10
c=50
The class D is privately derived from base class B. In private derivation, the public members of the base class
becomes private member of the derived class D. So the objects of D cannot have direct access to the public
member functions of B.
The function d.get_ab ( ), d.get_a ( ), d.show_a ( ) will not work in the main function.
Multilevel inheritance
The class A serves as a base class for derived class B which in turn serves as a base class for derived class C. The
class B is known as intermediate base class since it provides a link for the inheritance between A and C. The chain
ABC is known as inheritance path.
A derived class with multilevel inheritance is declared as follows:
class A { ….. }; //Base class
class B : public A{ ….. }; //B derived from A
class C : public B{ ….. }; //C derived from B
This can be extended to any number of levels.
Example: class student stores roll-number, class test stores the marks obtained in two subjects and class result
contains total marks obtained in the test. The class result can inherit the details of the marks obtained in the test
and the roll-number of students through multilevel inheritance.
#include<iostream>
Using namespace std;
class student
{
protected:
int roll_number;
public:
void get_number ( );
void put_number ( );
};
void student :: get_number (int a )
{
roll_number = a;
}
void student :: put_number ( )
{
Reshma, Dept of CSE
MODULE 3: Constructors, Destructors and Inheritance
cout<<”Roll Number: “ <<roll_number << “\n”;
}
class test : public student
{
protected:
float sub1;
float sub2;
public:
void get_marks (float, float );
void put_marks ( );
};
void test :: get_marks (float x, float y )
{
sub1 = x;
sub2 = y;
}
void test :: put_marks ( )
{
cout<<”Marks in SUB1 = “ <<sub1 << “\n”;
cout<<”Marks in SUB2 = “ <<sub2 << “\n”;
}
class result : public test
{
float total;
public:
void display;
};
void result :: display
{
total = sub1 + sub2;
put_number ( );
put_marks ( );
cout<<”Total = “<<total<<”\n”;
}
int main ( )
{
result student1;
student1.get_number (111);
student1.get_marks ( 75.0, 59.5);
student1.display ( );
return 0
}
Output:
Roll Number : 111
Marks in sub1 = 75
Reshma, Dept of CSE
MODULE 3: Constructors, Destructors and Inheritance
Marks in sub2 = 59.5
Total = 134.5
MULTIPLE INHERITANCE
A class can inherit the attributes of two or more classes as shown in figure. This is known as multiple inheritance.
It allows the user to combine the features of several existing classes.
In the above program Derived class P contain all the members of M and N in addition to its own members as
shown below.
class P
{
protected:
int m; // from M
int n; // from N
public:
void get_m ( ); // from M
void get_n ( ); // from N
void display ( ); // own member
};
int main ( )
{
B b;
b.display ( ); // invokes display ( ) in B
b.A :: display ( ); // invokes display ( ) in A
b.B :: display ( ); // invokes display ( ) in B
return 0
}
HIERARCHICAL INHERITANCE
Deriving more than one derived class from a single base class is called as hierarchical inheritance.
#include<iostream>
Using namespace std;
class student
{
Reshma, Dept of CSE
MODULE 3: Constructors, Destructors and Inheritance
protected:
int roll_number;
public:
void get_number ( );
void put_number ( );
};
void student :: get_number (int a )
{
roll_number = a;
}
void student :: put_number ( )
{
cout<<”Roll Number: “ <<roll_number << “\n”;
}
class test : public student
{
protected:
float sub1;
float sub2;
public:
void get_marks (float, float );
void put_marks ( );
};
void test :: get_marks (float x, float y )
{
sub1 = x;
sub2 = y;
}
void test :: put_marks ( )
{
cout<<”Marks in SUB1 = “ <<sub1 << “\n”;
cout<<”Marks in SUB2 = “ <<sub2 << “\n”;
}
class sports
{
protected:
float score;
public:
void get_score ( float s)
{
score=s;
}
void put_score ( )
{
cout<<”Sports “<<score<<”\n”;
Reshma, Dept of CSE
MODULE 3: Constructors, Destructors and Inheritance
}
};
class result : public test, public sports
{
float total;
public:
void display;
};
void result :: display
{
total = sub1 + sub2+score;
put_number ( );
put_marks ( );
put_score ( );
cout<<”Total = “<<total<<”\n”;
}
int main ( )
{
result student1;
student1.get_number (111);
student1.get_marks ( 75, 59);
student1.get_score(5);
student1.display ( );
return 0
}
Output:
Roll Number : 111
Marks in sub1 = 75
Marks in sub2 = 59
Score = 5
Total = 139
Multipath Inheritance
In the above example the class Child inherits the properties from 2 base classes Parent1 and Parent2 which is
derived from the common base class Grandparent. It can also inherit the properties of base class Grandparent as
shown by the broken line.
All the public and protected members of Grandparent class are inherited into Child class twice via Parent1
and Parent2. This means that Child class will have duplicate sets of members inherited from Grandparent. This
Reshma, Dept of CSE
MODULE 3: Constructors, Destructors and Inheritance
duplication can be avoided by making the common base class as virtual base class while declaring the direct or
intermediate base classes.
When a class is made a virtual base class, C++ sees to that only one copy of that class is inherited
regardless of multiple inheritance path between the virtual base class and a derived class.
Methods of Inheritance
Output
beta initialized
alpha initialized
gamma initialized
x=5
y = 10.75
m = 20
n = 30
beta is initialized first even though it appears second in the derived constructor, because it has been declared first
in the derived class header line. Also alpha(a) and beta(b) are function calls therefore parameters should not
include types.