C++ Module 3 & 4 Notes
C++ Module 3 & 4 Notes
Ashwini S
MODULE 3
INHERITANCE: . The mechanism of deriving a new class from an old one is called inheritance or
derivation. The old class is referred to as the base class and the new one is called the derived class or sub
class. The derived class inherits some or all of the traits from the base class.
A class can also inherit properties from more than one class or from more than one
level.Reusability is an important feature of OOP
A derived class can be defined by specifying its relationship with the base class in addition to
its own details.
The colon indicates that the derived class name is derived from the base-class-name. the visibility mode is
optional and if present, may be either private or protected or public. The default is private. Visibility
mode specifies whether the features of the base class are privately derived or publicly derived.
Types of Inheritance:
1.Single Inheritance
2.Multi level Inheritance
3.Mutiple Inheritance
4.Hybrid inheritance
5. Hierarchical Inheritance.
OOPS with C++ Garden City University Prof. Ashwini S
1.SINGLE INHERITANCE: one derived class inherits from only one base class. It is the most
simplest form of Inheritance.
A / /Base class
B //Derived class
#include<iostream>
using namespace std;
class A
{
public:
int a,b;
void get()
{
cout<<"Enter any two Integer values"<<endl;
cin>>a>>b;
}
};
class B:public A
{
int c;
public:
void add()
{
c=a+b;
cout<<a<<"+"<<b<<"="<<c;
}
};
int main()
{
B b;
b.get();
b.add();
}
Output:
Enter any two Integer values
12
1+2=3
OOPS with C++ Garden City University Prof. Ashwini S
2. MULTILEVEL INHERITANCE: In this type of inheritance the derived class inherits from a
class, which in turn inherits from some other class. The Super class for one, is sub class for the other.
A
#include<iostream.h>
class A
{
public:
int a,b;
void get()
{
cout<<"Enter any two Integer values"<<endl;
cin>>a>>b;
}
};
class B:public A
{
public:
int c;
void add()
{
c=a+b;
}
};
class C:public B
{
public:
void show()
{
cout<<a<<"+"<<b<<"="<<c;
}
};
int main()
{
C c;
c.get();
c.add();
c.show();
}
OOPS with C++ Garden City University Prof. Ashwini S
Output:
Enter any two Integer values
12 14
12+14=26
OOPS with C++ Garden City University Prof. Ashwini S
3. Multiple Inheritance:In this type of inheritance a single derived class may inherit from two or more
than two base classes.
A B
C
Syntax:
class D : visibility A, visibility B,….
{
………………
}
#include<iostream.h>
class A
{
public:
int a;
void getA()
{
cout<<"Enter an Integer value"<<endl;
cin>>a;
}
};
class B
{
public:
int b;
void getB()
{
cout<<"Enter an Integer value"<<endl;
cin>>b;
}
};
B C
#include<iostream.h>
class arithmetic
{
protected:
int num1, num2;
public:
void getdata()
{
cout<<"For Addition:";
cout<<"\nEnter the first number: ";
cin>>num1;
cout<<"\nEnter the second number: ";
cin>>num2;
}
};
class plus:public arithmetic
{
protected:
int sum;
public:
void add()
{
sum=num1+num2;
}
};
class minus
{
protected:
int n1,n2,diff;
public:
void sub()
{
cout<<"\nFor Subtraction:";
OOPS with C++ Garden City University Prof. Ashwini S
c
o
u
t
<
<
"
\
n
E
n
t
e
r
t
h
e
f
i
r
s
t
n
u
m
b
e
r
:
"
;
c
i
n
>
>
n
1
;
cout<<"\
nEnter
the
second
number:
";
OOPS with C++ Garden City University Prof. Ashwini S
cin>>n2;
diff=n1-n2;
}
};
class result:public plus, public minus
{
public:
void display()
{
cout<<"\nSum of "<<num1<<" and "<<num2<<"= "<<sum;
cout<<"\nDifference of "<<n1<<" and "<<n2<<"= "<<diff;
}
};
int main()
{
result z;
z.getdata();
z.add();
z.sub();
z.display();
}
For Addition:
Enter the first number: 1
For Subtraction:
Enter the first number: 3
Sum of 1 and 2= 3
Difference of 3 and 4= -1
B C D
#include<iostream.h>
class A //Base Class
{
public:
int a,b;
void getnumber()
{
OOPS with C++ Garden City University Prof. Ashwini S
cout<<"\n\nEnter Number :\t";
cin>>a;
}
};
class B : public A //Derived Class 1
{
public:
void square()
{
getnumber(); //Call Base class property
cout<<"\n\n\tSquare of the number :\t"<<(a*a);
}
};
class C :public A //Derived Class 2
{
public:
void cube()
{
getnumber(); //Call Base class property
cout<<"\n\n\tCube of the number :::\t"<<(a*a*a);
}
};
int main()
{
B b1; //b1 is object of Derived class 1
b1.square(); //call member function of class B
C c1; //c1 is object of Derived class 2
c1.cube(); //call member function of class C
}
Enter Number : 2
Square of the number : 4
Enter Number : 3
To create memory space for arrays:
pointer-variable = new data-type[size];
Ex: int *p = new int[10];
delete operator:
If the variable or object is no longer required or needed is destroyed by “delete” operator,
there by some amount of memory is released for future purpose. Synatx:
delete pointer-variable;
Eg: delete p;
If we want to free a dynamically allocated
array: delete [size] pointer-variable;
Program: write a program to find sum of list of integers
#include<iostream>
using namespace std;
int main()
OOPS with C++ Garden City University Prof. Ashwini S
{
int n,*p;
OOPS with C++ Garden City University Prof. Ashwini S
cout<<"Enter array size:";
cin>>n;
p=new int[n];
cout<<"Enter list of integers"<<endl;
for(int i=0;i<n;i++)
cin>>p[i];
//logic for summation
int s=0;
for( int i=0;i<n;i++)
s=s+p[i];
cout<<"Sum of array elements is\n";
cout<<s;
delete [ ]p;
return 0;
}
Enter array size:5
Enter list of integers
12345
Sum of array elements is
15
class item
{
int code;
float price;
public:
void getdata(int a,float b)
{
code=a;
price=b;
}
void show()
{
cout<<”code:”<<code<<”\n”<<”Price:”<<price<<endl;
}
};
b) using pointer
ptr->getdata(101,77.7);
ptr->show();
c) Using de referencing operator and dot operator
(*ptr).getdata(101,77.7);
(*ptr).show();
Above declaration creates memory space for an array of 10 objects of type item.
#include<iostream.h>
class item
{
int code;
float price;
public:
void getdata(int a,float b)
{
code=a;
price=b;
}
void show()
{
cout<<code<<"\t"<<price<<endl;
}
};
int main()
{
int n;
int cd;
float pri;
cout<<"Enter number of objects to be created:";
cin>>n;
item *ptr=new item[n];
item *p;
p=ptr;
for(int i=0;i<n;i++)
{
cout<<"Enter data for object"<<i+1;
cout<<"\nEnter Code:";cin>>cd;
cout<<"Enter price:";cin>>pri;
p->getdata(cd,pri);
p++;
}
OOPS with C++ Garden City University Prof. Ashwini S
p=ptr;
cout<<"Data in various objects are "<<endl;
cout<<"Sno\tCode\tPrice\n";
for(i=0;i<n;i++)
{
cout<<i+1<<"\t";
ptr->show();
ptr++;
}
return 0;
}
Pointers to Derived Classes: Pointers can be declared to derived class. it can be used to access
members of base class and derived class. A base class pointer can also be used to point to object of derived
class but it can access only members that are inherited from base class.
#include<iostream.h>
class base
{
public:
int a;
void get_a(int x)
{
a=x;
}
void display_a()
{
cout<<"In base"<<"\n"<<"a="<<a<<endl;
}
};
class derived:public base
{
int b;
public:
void get_ab(int x,int y)
{
a=x;
b=y;
}
void display_ab()
{
cout<<"In Derived "<<"\n"<<"a="<<a<<"\nb="<<b<<endl;
}
};
int main()
{
base b;
base *bptr;
bptr=&b;//points to the object of base class
bptr->get_a(100);
bptr->display_a();
derived d;
OOPS with C++ Garden City University Prof. Ashwini S
derived *dptr;
dptr=&d;//points to the object of derived class
dptr->get_a(400);
OOPS with C++ Garden City University Prof. Ashwini S
dptr->display_a();
dptr->get_ab(300,200);
dptr->display_ab();
return 0;
}
Output:
In base
a=100
In base
a=400
In Derived
a=300
b=200
In base
a=400
Polymorphism
Run time
Compile time
Polymorphism
Polymorphism
Polymorphism refers to the property by which objects belonging to different classes are able to
respond to the same message, but different forms. An essential requirement of polymorphism is therefore
the ability to refer to objects without any regard to their classes.
When we use the same function name in both the base and derived classes, the function in the bas
class is declared as virtual using the keyword virtual preceding its normal declaration.
When a function is made virtual, C++ determines which function to use at runtime based on the type of
object pointed to by the base pointer, rather than the type of the pointer. Thus, by making the base
pointer to point to different objects, we can execute different versions of the virtual function.
#include<iostream.h>
class Base
{
public:
void display()
{
cout<<”Display Base”;
}
virtual void show()
{
cout<<”Show Base”;
}
};
class Derived : public Base
{
public:
void display()
{
cout<<”Display Derived”;
}
void show()
{
cout<<”show derived”;
}
};
void main()
{
Base b;
Derived d;
Base *ptr;
cout<<”ptr points to Base”;
ptr=&b;
ptr->display(); //calls Base
ptr->show(); //calls Base
cout<<”ptr points to derived”;
ptr=&d;
ptr->display(); //calls Base
ptr->show(); //class Derived
}
OOPS with C++ Garden City University Prof. Ashwini S
Output:
Display Base
Show Derived
When ptr is made to point to the object d, the statement ptr->display(); calls only the function
associated with the Base i.e.. Base::display()
ptr->show();
calls the derived version of show(). This is because the function display() has not been made virtual
in the Base class.
When virtual functions are created for implementing late binding, observe some basic rules that
satisfy the compiler requirements.
OPERATOR OVERLOADING
C++ has the ability to provide the operators with as special meaning for a data type. The mechanism of
giving such special meanings to an operator is known as operator overloading. We can overload all the
operators except the following:
Class member access operator (“.” And ”
.*”) Scope resolution operator “::”
Size operator (sizeof)
Conditional operator
To define an additional task to an operator, specify what it means in relation to the class to which
the operator is applied. This is done with the help of a special function, called operator function.
The process of overloading involves following steps:
1. Create a class that defines the data type that is to be used in the overloading operation.
2. Declare the operator function operator op() in the public part of the class. It may be a member
function or a friend function.
3. Here op is the operator to be overloaded.
4. Define the operator function to implement the required operations.
OOPS with C++ Garden City University Prof. Ashwini S
General Form:-
Ex:
complex complex::operator+(complex c)
{
complex t;
t.real=real+c.real;
t.img=img+c.img;
return t;
}
Concept of Operator Overloading
One of the unique features of C++ is Operator Overloading. Applying overloading to operators means,
same operator in responding different manner. For example operator + can be used as concatenate
operator as well as additional operator.
Ex:
void operator-()
{
real=-real;
img=-img;
}
Syntax for Unary Operator (Outside a class)
return-type classname::operator operatorsymbol( )
{
//body of the function
}
Example 1:-
void operator++()
{
counter++;
}
Example 2:-
void complex::operator-()
{
real=-real;
img=-img;
}
The following simple program explains the concept of unary overloading.
#include < iostream.h >
#include < conio.h >
// Program Operator
Overloading class fact
{
int a;
public:
fact ()
OOPS with C++ Garden City University Prof. Ashwini S
{
a=0;
}
fact (int i)
{
a=i;
}
fact operator!()
{
int f=1,i;
fact t;
for (i=1;i<=a;i++)
{
f=f*i;
}
t.a=f;
return t;
}
void display()
{
cout<<”The factorial ”<< a;
}
};
void main()
{
int x;
cout<<”enter a number”;
cin>>x;
fact s(x),p;
p=!s;
p.display();
}
Explanation:
We have taken „!‟ as operator to overload. Here class name is fact. Constructor without parameters to
take initially value of „x‟ as 0. Constructor with parameter to take the value of „x‟ . We have create two
objects one for doing the factorial and the other for return the factorial. Here number of parameter for an
overloaded function is 0. Factorial is unary operator because it operates on one dataitem. operator
overloading find the factorial of the object. The display function for printing the result.
Example 1:-
Write a program to overload unary operator –
#include<iostream>
using namespace std;
class complex
{
OOPS with C++ Garden City University Prof. Ashwini S
float real,img;
public:
complex();
complex(float x, float y);
void display();
void operator-();
};
complex::complex()
{
real=0;img=0;
}
complex::complex(float x, float y)
{
real=x;
img=y;
}
void complex::display()
{
int imag=img;
if(img<0)
{
imag=-img;
cout<<real<<" -i"<<imag<<endl;
}
else
cout<<real<<" +i"<<img<<endl;
}
void complex::operator-()
{
real=-real;
img=-img;
}
int main()
{
complex c(1,-2);
c.display();
cout<<"After Unary - operation\n";
-c;
c.display();
}
Example 2:-
#include<iostream.h>
using namespace std;
class space
{
int x,y,z;
public:
void getdata(int a,int b,int c);
void display();
OOPS with C++ Garden City University Prof. Ashwini S
void operator-();
};
void space :: getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
void space :: display()
{
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
cout<<"z="<<z<<endl;
}
void space :: operator-()
{
x=-x;
y=-y;
z=-z;
}
int main()
{
space s;
s.getdata(10,-20,30);
s.display();
-s;
cout<<"after negation\n";
s.display();
}
Output:
x=10
y=-20
z=30
after negation
x=-10
y=20
z=-30
Example 3:-
Unary minus operator using a friend function
#include<iostream.h>
#include<iostream.h>
using namespace std;
class space
{
int x,y,z;
public:
OOPS with C++ Garden City University Prof. Ashwini S
void getdata(int a,int b,int c);
void display();
friend void operator-(space &);
};
void space :: getdata(int a,int b,int c)
{
x=a;
y=b;
z=c;
}
int main()
{
space S;
S.getdata(10,-20,30);
S.display();
-S;
cout<<"after negation\n";
S.display();
}
Output:
10 -20 30
after negation
-10 20-30
Example
complex operator+(complex s)
{
complex t;
t.real=real+s.real;
t.img=img+s.img;
return t;
}
The following program explains binary operator overloading:
#include < iostream.h >
#include < conio.h >
class sum
{
int a;
public:
sum()
{
a=0;
}
sum(int i)
{
a=i;
}
sum operator+(sum p1)
{
sum t;
t.a=a+p1.a;
return t;
}
void main ()
{
cout<<”Enter Two Numbers:”
int a,b;
cin>>a>>b;
sum x(a),y(b),z;
z.display();
z=x+y;
cout<<”after applying operator \n”;
z.display();
getch();
}
Output for the above program:
Enter two numbers 5 6
After applying operator
OOPS with C++ Garden City University Prof. Ashwini S
The sum of two numbers 11
Explanation: The class name is „sum‟ . We have create three objects two for to do the sum and the other
for returning the sum. ‟ +‟ is a binary operator operates on members of two objects and returns the result
which is member of a object.here number of parameters are 1. The sum is displayed in display function.
Write a program to over load arithmetic operators on complex numbers using member function
#include<iostream.h>
class complex
{
float real,img;
public:
complex(){ }
complex(float x, float y)
{
real=x;
img=y;
}
complex operator+(complex c)
void display();
};
complex complex::operator+(complex c)
{
complex temp;
temp.real=real+c.real;
temp.img=img+c.img;
return temp;
}
void complex::display()
{
int imag=img;
If(img<0)
{
imag=-imag;
cout<<real<<”-i”<<imag;
}
else
cout<<real<<”+i”<<img;
}
int main()
{
complex c1,c2,c3;
c1=complex(2.5,3.5);
c2=complex(1.6,2.7);
c3=c1+c2;
c3.display();
return 0;
}
Overloading Binary Operators Using Friends
Exception handling
Exceptions: Exceptions are runtime anomalies or unusual conditions that a program may encounter while
executing .Anomalies might include conditions such ass division by zero, accessing an array outside of
its bounds or running out of memory or disk space. When a program encounters an exception condition,
it must be identified and handled.
Exceptions provide a way to transfer control from one part of a program to another. C++
exception handling is built upon three keywords: try, catch, and throw.
1. Synchronous exceptions:Errors such as “Out-of-range index” and “over flow” are synchronous
exceptions
2. Asynchronous exceptions: The errors that are generated by any event beyond the control of the
program are called asynchronous exceptions
The purpose of exception handling is to provide a means to detect and report an exceptional circumstance
C++ exception handling is built upon three keywords: try, catch, and throw.
Try is used to preface a block of statements which may generate exceptions. This block of statements is known
as try block. When an exception is detected it is thrown by using throw statement in the try block. Catch block
catches the exception thrown by throw statement in the try block and handles it appropriately.
OOPS with C++ Garden City University Prof. Ashwini S
#include<iostream>
using namespace std;
int main()
{
int a,b;
cout<<"Enter any two integer values";
cin>>a>>b;
int x=a-b;
try
{
if(x!=0)
{
cout<<"Result(a/x)="<<a/x<<endl;
}
else
{
throw x;
}
}
catch(int ex)
{
cout<<"Exception caught:Divide By Zero \n";
}
}
THROWING MECHANISM
When an exception is detected, it can be thown by using throw statement in any one of the following forms
throw(exception);
throw exception;
OOPS with C++ Garden City University Prof. Ashwini S
throw;
OOPS with C++ Garden City University Prof. Ashwini S
CATCHING MECHANISM:
• When an exception is thrown, the exception handler are searched in order fore an appropriate
match.
• It is possible that arguments of several catch statements match the type of an exception. In
such cases the first handler that matches the exception type is executed
cout<<"caught an integer"<<endl;
}
OOPS with C++ Garden City University Prof. Ashwini S
catch(double d)
{
cout<<"caught a double"<<endl;
}
}
int main()
{
test(1);
test(0);
test(-1);
test(2);
return 0;
}
Output:
caught an integer
caught a character
caught a double
end of try block
all possible types of exceptions and therefore may not be able to design independent catch handlers to
catch them. In such circumstances, we can force a catch statement to catch all exceptions instead of a
certain type alone.
catch(…)
{
………
}
return 0;
}
Re-throwing an Exception:
It is possible to pass exception caught by a catch block again to another exception handler. This
I known as Re-throwing.
#include <iostream>
using namespace std;
void MyHandler()
{
try
{
throw "hello";
}
catch (const char*)
{
cout <<"Caught exception inside MyHandler\n";
throw; //rethrow char* out of function
}
}
int main()
{
cout<< "Main start ... "<<endl;
try
{
MyHandler();
}
catch(const char*)
{
cout <<"Caught exception inside Main\n";
}
cout << "Main end";
return 0;
}
Specifying Exceptions:
Specification of exception restrict functions to throw some specified exceptions only with the use
of throw(exception list) in the the header of the function.
General form
Type function_name(argument list) throw(exceptions -list)
{
Statements
try
{
statements
}
OOPS with C++ Garden City University Prof. Ashwini S
}
#include <iostream>
using namespace std;
OOPS with C++ Garden City University Prof. Ashwini S
void test(int x) throw(int,float,char)
{
switch(x)
{
case 1:throw x;
break;
case 2:throw 'x';
break;
case 3:throw double(x);
break;
case 4:throw float(x);
break;
}
}
int main()
{
try
{
test(4);//test(4) leads to abnormal termination
}
catch(int i)
{
cout <<"Caught int type exception\n";
}
catch(float f)
{
cout <<"Caught float type exception\n";
}
catch(char c)
{
cout <<"Caught char type exception\n";
}
catch(double i)
{
cout <<"Caught Double type exception\n";
}
return 0;
}