Object Oriented Concepts
Object Oriented Concepts
Course Objective
Digitech Technologies 1
Object Oriented Concepts
Digitech Technologies 2
Object Oriented Concepts
What is an Object ?
An object
Is an unique, identifiable, self-contained entity that
contains attributes and behaviors.
Examples
Car ,Telephone , Pen etc
Digitech Technologies 3
Object Oriented Concepts
Digitech Technologies 4
Object Oriented Concepts
Abstraction
The process of forming general and relevant concepts from a
more complex scenario
Engine Driving
Digitech Technologies 5
Object Oriented Concepts
Binary Counter
U/D B1
Capacitor Buffer
Reset B8
Resistor
Inverter
Carry out
ENB
AND Gate
Diode Register
A Q1
XOR Gate
H Q8
Transistor
OR Gate ENB
MOSFET Boolean Logic Gates Digital circuits built Central Processing unit -
built using basic using Boolean logic Built using complex
Basic Electronic electronic components gates digital circuits
Components (1st Level abstraction) nd rd
(2 Level abstraction) (3 level abstraction)
Digitech Technologies 6
Object Oriented Concepts
Encapsulation
“En” = “In a”
Encapsulate = “In a Capsule”
Digitech Technologies 7
Object Oriented Concepts
public,
private etc.
Typically in a class
Digitech Technologies 8
Object Oriented Concepts
Relationships
Digitech Technologies 9
Object Oriented Concepts
Loan
-LoanAmount : double
Is-A Relationship - Inheritance -InterestRate : float
-Duration : int
-CustomerID : int
Inheritance refers to a class replicating some +GetInterestRate() : float
+GetLoanAmount() : double
+GetDuration() : int
Inherits
The class which inherits from another
class is called as ‘derived class’ Wealth
Digitech Technologies 10
Object Oriented Concepts
Loan
Digitech Technologies 11
Object Oriented Concepts
Multiple Inheritance
FuelCar ElectricCar
-TankCapacity : float -BatteryCapacity : float
-TypeOfFuel : char
HybridCar
Digitech Technologies 12
Object Oriented Concepts
Advantages
Promotes reusability
Disadvantages
Digitech Technologies 14
Object Oriented Concepts
Message Passing
Example:
Polymorphism
Poly = ‘many’
morph = ‘form’
What is a Class ?
A Class
Examples :
Digitech Technologies 17
Object Oriented Concepts
Class Contains …
State (Member variables)
•Variables defined inside a class form the State of the class
•Not exposed to external world
Behavior (Member Methods)
•Behavior exhibited by the classte (BEHAVIOR) Interface to external
world (Through
a
ler Methods/ Functions
to external world ce Current only)
Ac Number Gear
of Gears 3
) w
Ch
wn lo
4
Do e (S
an
ak
G
Br
ea
r
Digitech Technologies 18
Object Oriented Concepts
object class
Class Student
Name
Regn_No
setName()
Jodie Daria Jane Brittany setRegnNo()
R001 R002 R003 R004
CalcMarks()
Digitech Technologies 19
Object Oriented Concepts
Method Overloading
Example:
Digitech Technologies 20
Object Oriented Concepts
Method Overriding
Example 1:
A base class ‘Shape’ has function ‘Draw’ which draws the shape
on screen
The derived classes Line, Rectangle, Circle etc. implement their
own ‘Draw’ methods which draw respective shapes on screen
Digitech Technologies 21
Object Oriented Concepts
Housing Loan
-InterestType : char
+GetInterestType() : char
+SetInterestType() Housing
+Report() Loan
Report
Digitech Technologies 22
Structured Programming (Procedure-Oriented)
Digitech Technologies 24
Procedural versus Object Oriented Programming
Digitech Technologies 25
Object Oriented Concepts
Digitech Technologies 26
Basics of C++
Digitech Technologies 27
cin and cout Basics
cin and cout are objects of C++, used with standard input and
standard output device.
cin and cout objects use >> and << operators. The << is referred
to as the insertion operator and >> operator is called extraction
operator.
cin and cout objects with >> and << are similar to scanf and printf
#include<iostream.h>
#include<stdio.h>
int main()
{ Output
printf("%d %c\n",65,65); 65 A
cout<<65<<" "<<(char)65<<endl;
return 0; 65 A
}
Digitech Technologies 28
cin and cout Basics
#include<iostream.h> output
Enter two numbers 45 Hello
void main() Invalid input
{
int a,b; Enter two numbers 45 55
100
cout<<"Enter two numbers ";
cin>>a>>b;
if( cin.good() )
cout << a+b << endl;
else
cout << "Invalid input\n";
cin.clear();
}
Digitech Technologies 29
Data types of C++
Digitech Technologies 30
C++ comments
Example:
/****************************************************
* This style of commenting is used for functions and files
*****************************************************/
Example:
// This is for single line comment
fArea = fRadius * fRadius * PI ; // calculating area of Circle
Digitech Technologies 31
Control Structures
– switch case
– for loop
– while loop
– do while
Digitech Technologies 32
C and C++ differences
#include<iostream.h>
#include<stdio.h>
int a=100;
void main()
{ output
int a=45; 78 45 100
int printf=78; 55
int cout=55;
::cout<<cout<<endl;
}
Digitech Technologies 34
C and C++ differences
syntax : (data_type)expr
C++ syntax : data_type(expr)
#include<stdio.h>
void main() Output
{
44
int a=300;
char b; 44
b=a; 44
printf(“%d\n”,b);
printf(“%d\n”,(char)a);
printf(“%d\n”,char(a)); Digitech Technologies 35
}
C and C++ differences
Logical constant
Physical constant
Digitech Technologies 36
C and C++ differences
efault arguments
Digitech Technologies 37
C and C++ differences
Default arguments
#include<iostream.h>
void abc(int=100,int=200);
void main()
{
abc();
abc(10);
abc(10,20);
} Output
100 200
void abc(int a,int b) 10 200
{ 10 20
cout << a << " " << b <<endl;
}
Digitech Technologies 38
C and C++ differences
Function overloading
Digitech Technologies 39
C and C++ differences
Reference variables
#include<iostream.h>
void main()
{
int a=200;
int &b=a;
output
cout << &a << " " << &b <<endl; 0x0012FF7C 0x0012FF7C
a=10;
20 20
b=20;
cout << a << " " << b << endl;
}
Digitech Technologies 40
C and C++ differences
#include<iostream.h> #include<iostream.h>
Digitech Technologies 41
C and C++ differences
#include<iostream.h>
int main()
{
int x=90;
cout << x << endl; Output
abc(x)=300;
90
cout << x << endl;
return 0;
300
}
Digitech Technologies 42
Objects
Digitech Technologies 43
Objects
Definitions
Digitech Technologies 44
Objects
State
Behavior
The behavior groups all the abilities of an object and describes the
actions and reactions of that object. Each individual behavioral
component is called an operation.
The operations of an object are triggered as a result of an
external event, represented in the form of a message sent by
another object.
Digitech Technologies 45
C++ struct and class
as methods.
et_time();
ere as
ass type.
Digitech Technologies 46
Abstraction
private:
A private member can be accessed only from within
the class members.
public:
A public member can be accessed from any where.
protected:
A protected member is same as private member to the
class but it can be accessed in derived type.
Digitech Technologies 47
Access specifiers in a class
public: Can be accessed within the class or from outside of the class
Methods that define the behavior of the object and are accessed by
other classes are made public
Methods which are invoked only within the class and not required
to be invoked externally are usually made private
– They are called helper methods
Digitech Technologies 48
class and struct keywords
Examples:
Digitech Technologies 50
Constructor (object initialization)
Using class we can create a complex object that have some hidden
data and a set of well defined member funcions.
If the object have legal value, then the member functions can
maintain the object’s state.
If a class does not have any constructor , then C++ adds default
constructor without any statements in it.
Digitech Technologies 52
Constructor
Digitech Technologies 53
Destructor
• No arguments
• No return value
• Cannot be overloaded
class employee
{
:
~employee()
{
}
Digitech Technologies 54
Named and anonymous objects
class_name var;
// implicitly calls default constructor
class_name var(value1,..);
// implicitly calls overloaded constructor
class_name();
// unnamed default object
class_name(v1,v2);
// unnamed initialized object
Digitech Technologies 55
Anonymous Object
Digitech Technologies 57
Constant data members
class class_name
{
class_name( ... ) : mem1(val1),mem2(val2) ...
{
}
:
};
Digitech Technologies 58
Constant member functions
Accessor methods
Accessor methods can not modify the active object state.
Mutator methods
Mutator methods can modify the active object state.
Digitech Technologies 59
Constant members
Digitech Technologies 60
Object property types
Fixed property
A copy of fixed data member is given to every
instance of the class. Once the member initialized,
it cannot be modified ( const data members )
Shared property
A single copy of the data member is created and
it is used by all instances of the class type
( static data members )
Digitech Technologies 61
Static data member
class demo
{ Size of the class demo is four bytes
static int num; but not eight.
int color;
public: Size of a class is the sum of the
: sizes of non-static data members
};
Int demo::num=45;
Digitech Technologies 62
Static Member Functions
class demo
{ void main()
static int num; {
int color; demo d(77),e(88);
public: cout << d.getColor() << endl;
demo(int a):color(a){} cout << e.getColor() << endl;
static int getNum() cout << demo::getNum();
{ }
return num;
}
int getColor(){ return color; }
};
Int demo::num=45;
Digitech Technologies 63
Static Members
Digitech Technologies 64
Memory Allocation for Classes and Objects
Member functions
are assigned GetEmployeeNumber();
common memory GetEmployeeName();
location to all objects SetEmployeeNumber(int);
SetEmployeeName(char*)
m_iEmpNum;
char* m_pcEmpName
m_iEmpNum;
char* m_pcEmpName
EmployeeThree
m_iEmpNum; EmployeeTwo
char* m_pcEmpName
Data members are
EmployeeOne assigned seperate
memory locations for
seperate objects
Digitech Technologies 65
this pointer
It points to the current object, the object that invoked the method.
Digitech Technologies 66
this pointer
The answer lies in the fact that the a member function implicitly
uses a special pointer ‘this’ which a hidden parameter to the
member function.
this->member
Digitech Technologies 67
this pointer
#include<iostream.h> #include<iostream.h>
Digitech Technologies 70
Coding standards and naming conventions
Digitech Technologies 71
Coding standards and naming conventions
Names of functions:
class Date
{
private:
//Data members
public:
short GetDayOfMonth ();
char* GetDateOfWeek ();
};
Digitech Technologies 72
Coding standards and naming conventions
Digitech Technologies 73
Coding standards and naming conventions
Commenting Guidelines
File Header Block : All the source and header files must have the
header information as shown in the format below. The code must
not exceed 80 columns width
/****************************************************
* File : <filename>
* Description : <description>
* Author : <author> <company>
* Version : <version number>
* Date : <Date>
* Modification log :
****************************************************/
File Footer Block : All files should have this footer at the end
of the file.
/****************************************************
* End of <filename>
****************************************************/
Digitech Technologies 74
Coding standards and naming conventions
Commenting Guidelines
/*********************************************************
* Function: <Function Name>
* Description: <Overview of the function>
* Input Parameters:
* <Parameter 1> – <brief description>
* <Parameter 2> - <brief description>
* ... ... ... ... ... ... ... ...
* Returns : <Return values both in case of success and
* error conditions if the function returns something>
*********************************************************/
Digitech Technologies 75
Coding standards and naming conventions
/*******************************************************
* FileName: Employee.h
* Author: E&R Department, Digitech Technologies Limited
* Date: 03-Sep-2007
* Description: Declares the class ‘Employee’.
*******************************************************/
#include<stdio.h>
#include <malloc.h>
#ifndef _EMPLOYEE_H
#define _EMPLOYEE_H
class Employee
{
private:
int m_iEmpNum;
char m_acEmpName[25];
Digitech Technologies 76
Coding standards and naming conventions
public:
//Method to get the Employee number
int GetEmployeeNumber();
#endif // _EMPLOYEE_H
/******************************************************
* End of Employee.h
*******************************************************/
Digitech Technologies 77
Coding standards and naming conventions
/**********************************************************
* FileName: Employee.cpp
* Author: E&R Department, Infosys Technologies Limited
* Date: 01-Jul-2005
* Description: Implements the class ‘Employee’.
**********************************************************/
#include "Employee.h“
/**********************************************************
* GetEmployeeNumber
* PARAMETERS: None
* RETURNS: int m_iEmpNum
**********************************************************/
int Employee::GetEmployeeNumber()
{
return m_iEmpNum;
}
Digitech Technologies 78
Coding standards and naming conventions
/**********************************************************
* GetEmployeeName
* PARAMETERS: None
* RETURNS: char* m_acEmpName
**********************************************************/
const char * Employee::GetEmployeeName()
{
return m_acEmpName;
}
/**********************************************************
* SetEmployeeNumber
* PARAMETERS:
* int iEmpNum- Employee Number
* RETURNS: Nothing
**********************************************************/
void Employee::SetEmployeeNumber(int iEmpNum)
{
m_iEmpNum=iEmpNum;
}
Digitech Technologies 79
Coding standards and naming conventions
/*****************************************************
* SetEmployeeName
* PARAMETERS:
* char* pcEmpName- Employee name (String)
* RETURNS: Nothing
*****************************************************/
/*****************************************************
* End of Employee.cpp
*****************************************************/
Digitech Technologies 80
Method chaining(returning current obj. reference)
#include<iostream.h> demo& putTwo(int k)
class demo {
{ num=k;
int num; return *this;
public: }
demo():num(0){} };
demo(int k):num(k){}
void show(){ cout<<num<<endl; }
demo setOne(int k) void main ()
{ {
num=k; demo d1(45),d2(45);
return *this;
} d1.setOne(20).setTwo(30);
demo setTwo(int k) d2.putOne(20).putTwo(30);
{
num=k; d1.show();
return *this; d2.show();
} }
demo& putOne(int k) Output
{ num=k; 20
return *this; 30
}
Digitech Technologies 81
Aggregation
Digitech Technologies 82
C++ Dynamic Allocation Operators
The new and delete operators are used to allocate and free
memory at run time.
• Suppose the allocated memory is not freed then this space will
remain allocated even after the execution of the program. Such
memory spaces could be very dangerous and may lead to the
system crash due to lack of free memory.
Digitech Technologies 84
Best Practices in using new and delete operators
• All the memory allocations that happen within the class needs to
be deallocated within the destructor.
Digitech Technologies 85
String class
Digitech Technologies 86
Copy constructor
Digitech Technologies 87
Copy constructor
Digitech Technologies 89
Inline Functions
class Rectangle
{
double Length;
double Breadth ;
public:
inline double CalcArea() { … }
void Show(){ … } // is also inline function
void Display(); // while defining, should be decl. inline
};
Digitech Technologies 90
Friend Functions
Digitech Technologies 91
Friend Functions
Digitech Technologies 92
Friend Class
Digitech Technologies 93
Friend Functions
Digitech Technologies 94
Operator overloading
str a; str a;
a.copy(“Hello”); a=“Hello”;
a.add(“Abc”); a+“Abc”;
Digitech Technologies 95
Operator overloading
Digitech Technologies 96
Operator overloading
Syntax:
data_type operator opr_char( [ data_type p1 ] [, data_type p2 ] )
{
}
Digitech Technologies 97
Operator overloading
Digitech Technologies 98
Operator overloading
#include<iostream.h>
#include<string.h>
class str
{
char *s;
public:
str() { s=new char(0); }
str(char *a) { s=new char[ strlen(a)+1 ]; strcpy(s,a); }
void display() { cout<<s<<endl; }
char* operator=(char *a)
{ delete s;
s=new char[ strlen(a)+1 ]; strcpy(s,a);
return a;
}
char* operator+(char *a)
{ char *t=new char[ strlen(s)+strlen(a)+1 ];
strcpy(t,s);
strcat(t,a);
return t;
}
friend char* operator+(char*,str);
Digitech Technologies 99
};
Operator overloading
char* operator+(char *a, str x)
{
char *t=new char[ strlen(a)+strlen(x.s)+1 ];
strcpy(t,a);
strcat(t,x.s);
return t;
}
void main()
{ Output
str a,b(“hello”),c,d,e;
e=a=”abc”; abc
c=b+”xyz”;
d=”123”+b; hello
helloxyz
a.display(); 123hello
b.display(); abc
c.display();
d.display();
e.display();
}
Digitech Technologies 100
Ellipsis (…)
After creating the list variable, the list need initalized using
va_start( va_list , the last known parameter name )
#include<iostream.h>
#include<stdarg.h>
#include<iostream.h>
class demo
{
int n1,n2;
public:
demo(int a,int b):n1(a),n2(b){}
operator int() { return n1+n2; }
};
void main()
{ demo d(45,55);
int k;
k=d;
cout << k << endl; // 100
}
Digitech Technologies 106
Operator overloading
Example for User-defined to User-defined conversion
#include<iostream.h> fahrenheit::operator celsius()
class celsius; {
class fahrenheit return (f-32.0)*5.0/9.0;
{ }
float f;
public: void main()
fahrenheit():f(0){} {
fahrenheit(float a):f(a){} celsius a,b(30);
void display(){ cout<<f<<endl; } fahrenheit c,d(100);
operator celsius();
}; a=(celsius)d;
c=(fahrenheit)b;
class celsius
{ a.display();
float c; b.display();
public: c.display();
celsius():c(0){} d.display();
celsius(float a):c(a){} }
void display(){ cout<<c<<endl; }
operator fahrenheit() { return c*9.0/5.0 + 32.0; }
};
Digitech Technologies 107
Inheritance
• The old class is referred to as the base class and the new class is
called the derived class or subclass.
• All the objects in this world come under some kind of classification.
Inheritance allows the creation of hierarchical classification.
Inheritance Relationship
• Trainee is an Employee
Employee
Trainee
public public
protected protected
public protected
protected protected
Protected Members
Protected Members
Advantages:
Disadvantages:
• No validity checking
- Derived class can assign illegal value
• Implementation dependent
- Derived class member functions more likely dependent on
base class implementation
- Base class implementation changes may result in derived
class modifications resulting in Fragile (brittle) software
Digitech Technologies 116
Inheritance
The derived class constructor must tell the Compiler which base class
constructor to use for base class member initialization. This is provided by
using base class parameter list:
class base
{ void main()
int num; {
public: derive d(45);
base():num(0){}
base(int k):num(k){} d.show();
void show() d.display();
{ cout<<num<<endl; } }
};
ethod Overriding
class base
{ void main()
int num; {
public: derive d(45);
base():num(0){}
base(int k):num(k){} d.base::show();
void show() d.show();
{ cout<<num<<endl; } }
};
derive derive::operator=(int a)
{
base::operator=(a); // calling base assignment operator overloading
:
:
}
#include<iostream.h>
Output:
class base from base default
{ from derive default
public: from base copy const
base() { cout<<"from base default\n"; } from derive copy const
base(base &a) { cout<<"from base copy const\n"; } from derive destructor
~base() { cout<<”from base destructor\n”; } from base destructor
}; from derive destructor
class derive : public base from base destructor
{
public:
derive(){ cout<<"from derive default\n"; }
derive(derive &a) : base(a) { cout<<"from derive copy const\n"; }
~derive(){ cout<<”from derive destructor\n”; }
};
void main()
{
derive a;
derive b=a;
}
Digitech Technologies 125
Inheritance
Multiple Inheritance
C++ allows a class derived from more than one base or parent
classes. The derived class will have all the members of the base
classes. The base classes may have members with same name.
Use base class name and scope resolution operator ( :: ) to avoid
ambigious member reference.
Virtual Inheritance
Suppose a class DERIVE is derived from two different base
classes BASE1 and BASE2, which in turn are derived from the
same base class COMMON_BASE. It is clear that the DERIVE
class will have two copies of COMMON_BASE class members.
Virtual inheritance can solve the above problem.
When a class derives several times from the same virtual base class,
this derive class will have only one copy of the base class.
Digitech Technologies 126
Inheritance
#include<iostream.h>
#include<iostream.h>
#include<string.h>
class employee
{
char name[20];
char grade;
public:
employee(){}
employee(char *a,char b):grade(b) { strcpy(name,a); }
void display()
{
cout<<name<<” “<<grade<<” “;
}
char getgrade(){
return grade;
}
};
Digitech Technologies 129
Inheritance - Example
public:
manager(){}
manager(char *a,int b):employee(a,’A’),sal(b){}
void display()
{
employee::display();
cout<<sal<<” “;
}
int pay()
{
return sal;
}
};
public:
wage_employee(){}
wage_employee(char *a,int b,int c):employee(a,’C’), hours(b),rate(c){}
void display()
{
employee::display();
cout<<hours<<” “<<rate<<” “;
}
int pay(){ return hours*rate; }
protected:
wage_employee(char *a,int b,int c,char d):employee(a,d),
hours(b),rate(c){}
};
void main()
{
manager m[50];
wage_employee w[50];
sales_person s[50];
char ch,name[20];
int mmax,smax,wmax,sal,hours,rate,comm,sales;
mmax=wmax=smax=0;
while( ch!='q' )
{
cout<<"\nwage employee sales person manager quit ";
cin>>ch; cin.get();
if(ch=='m')
{
cout<<"Enter salary "; cin>>sal;
cin.get();
m[mmax]=manager(name,sal); mmax++;
}
if(ch=='w' || ch=='s')
{
cout<<"Enter hours ";
cin>>hours;
cout<<"Enter rate ";
cin>>rate; cin.get();
if(ch=='w')
{
w[wmax]=wage_employee(name,hours,rate);
wmax++;
}
Digitech Technologies 134
Inheritance - Example
if(ch=='s')
{
cout<<"Enter comm ";
cin>>comm;
cout<<"Enter sales ";
cin>>sales;
cin.get();
s[smax]=sales_person(name,hours,rate,comm,sales);
smax++;
}
}
}
}
void main()
{
employee *e[150];
char ch,name[20];
int max,sal,hours,rate,comm,sales;
max=0;
while( ch!='q' )
{
cout<<"\nwage employee sales person manager quit ";
cin>>ch;
cin.get();
if(ch=='m')
{
cout<<"Enter salary "; cin>>sal;
cin.get();
e[max]=new manager(name,sal);
max++;
}
if(ch=='w' || ch=='s')
{
cout<<"Enter hours ";
cin>>hours;
cout<<"Enter rate ";
cin>>rate; cin.get();
if(ch=='w')
{
e[max]=new wage_employee(name,hours,rate);
max++;
}
Digitech Technologies 138
Inheritance - Example
if(ch=='s')
{
cout<<"Enter comm ";
cin>>comm;
cout<<"Enter sales ";
cin>>sales;
cin.get();
e[max]=
new sales_person(name,hours,rate,comm,sales);
max++;
}
}
}
}
int i;
for(i=0;i<max;i++)
{
switch( e[i]->getgrade() )
{
case 'A': ((manager*)e[i])->display();
cout<<endl;
break;
case 'B': ((sales_person*)e[i])->display();
cout<<endl;
break;
case 'C': ((wage_employee*)e[i])->display();
cout<<endl;
break;
}
} The code repetition problem still exists
}
Polymorphism - Binding
#include<iostream.h>
#include<string.h>
void main()
{
employee *e=new sales_person("Ravi Kumar",5,90,500,102);
e->display();
cout<<endl;
((sales_person*)e)->display();
cout<<endl;
} output
Ravi Kumar B
Ravi Kumar B 5 90 500 102
#include<iostream.h>
#include<string.h>
void main()
{
employee *e=new sales_person("Ravi Kumar",5,90,500,102);
e->display();
cout<<endl;
((sales_person*)e)->display();
cout<<endl;
} output
Ravi Kumar B 5 90 500 102
Ravi Kumar B 5 90 500 102
• Instead of making type casting the pointer the same effect can be
got by defining the overridden methods as virtual in the base class
class employee
{
virtual void display();
class employee
{
:
public:
employee(){}
employee(…){…}
virtual void display(){ … }
};
:
: Compiler Error:
void main() 'pay' : is not a member of 'employee'
{
employee *e=new sales_person("Ravi Kumar",5,90,500,102);
e->display();
cout<<e->pay()<<endl;
}
class employee
{
:
public:
employee(){}
employee(…){…}
virtual void display(){ … }
virtual int pay(){ return 0; }
};
: Output
: Ravi Kumar B 5 90 500 102 950
void main()
{
employee *e=new sales_person("Ravi Kumar",5,90,500,102);
e->display();
cout<<e->pay()<<endl;
}
Digitech Technologies 147
Polymorphism
class employee
{
:
virtual void display(){ … }
virtual int pay(){ return 0; } manager pay
};
class manager : public employee
{
:
public:
// int pay(){ return sal; } Output
}; Ravi Kumar A 19000 0
:
void main()
{
employee *e=new manager("Ravi Kumar",19000);
e->display();
cout<<e->pay()<<endl;
}
Digitech Technologies 148
Polymorphism
Abstract class
Example:
virtual int pay()=0;
class employee
{
:
virtual void display(){ … }
virtual int pay()=0;
};
class manager : public employee
{
:
public:
// int pay(){ return sal; } Compiler Error:
}; 'manager' : cannot instantiate abstract class
:
void main()
{
employee *e=new manager("Ravi Kumar",19000);
e->display();
cout<<e->pay()<<endl;
}
Digitech Technologies 150
Polymorphism
class employee
{
:
virtual void display(){ … }
virtual int pay()=0;
};
class manager : public employee
{
:
public:
int pay(){ return sal; } Output:
}; Ravi Kumar A 19000 19000
:
void main()
{
employee *e=new manager("Ravi Kumar",19000);
e->display();
cout<<e->pay()<<endl;
}
Digitech Technologies 151
Polymorphism
#include<iostream.h>
class shape Shape Example
{ public:
virtual int area()=0;
};
class circle : public shape
{
int r;
public:
circle(int a):r(a){}
int area() { return 22.0/7.0*r*r; }
};
class square : public shape
{
int s;
public:
square(int a):s(a){}
int area() { return s*s; }
};
Digitech Technologies 152
Polymorphism
sort::bubble((sortable**)e,MAX);
for(int i=0;i<MAX;i++)
e[i]->show(); Output
} Sham --- 8000
Ravi --- 9000
Sing --- 10000
Neha --- 11000
Giri --- 12000
class base
{
public:
~base(){ cout<<"from base destructor\n"; }
};
class derive : public base
{
public:
~derive(){ cout<<"from derive destructor\n"; }
};
class base
{
public:
virtual ~base(){ cout<<"from base destructor\n"; }
};
class derive : public base
{
public:
~derive(){ cout<<"from derive destructor\n"; }
};
Examples:
Out-of-bound array subscript, arithmetic overflow or underflow,
division by zero, out of memory, invalid function parameter, etc.,
• The catch block must immediately follow the try block that
throws the exception.
:
try
{
:
if( … ) throw exception;
:
}
catch (type argument)
{
:
}
:
void main()
{
int a,b,c;
char ch;
try
{
while( 5 )
{
cout<<"Enter two numbers ";
cin>>a>>b;
try
{
• Eliminate code duplication for different types and thus make the
software development easier and more manageable.
#include<iostream.h>
#include<string.h>
template<class T>
void bubble(T **e,int max)
{
T *t;
int i,k;
for(i=0;i<max-1;i++)
for(k=0;k<max-i-1;k++)
if( e[k]->compare(e[k+1]) > 0 )
{
t=e[k];
e[k]=e[k+1];
e[k+1]=t;
}
}
class employee
{
char name[20];
int sal;
public:
employee(){}
employee(char *a,int b):sal(b)
{
strcpy(name,a);
}
void show()
{
cout<<name<<" --- "<<sal<<endl;
}
int compare(employee *k)
{
return sal-k->sal;
}
};
#define MAX 5
void main()
{
employee *e[MAX]={ new employee("Ravi",9000),
new employee("Giri",12000),
new employee("Sham",8000),
new employee("Sing",10000),
new employee("Neha",11000) };
bubble(e,MAX);
Output
for(int i=0;i<MAX;i++) Sham --- 8000
e[i]->show(); Ravi --- 9000
} Sing --- 10000
Neha --- 11000
Giri --- 12000
#include<iostream.h>
#include<stdarg.h>
#include<stdlib.h>
n=new T[max];
for(int i=0;i<max;i++) n[i]=va_arg(x,T);
}
T& operator[](int a)
{
a=a-s;
if(a<0 || a>=max ) { cout<<"error in index"<<endl; exit(1); }
return n[a];
} Output
};
56 7 89 45 33 8 9 32 11 30
void main() Hello Welcome
{
array<int,0> a(10,56,7,89,45,33,8,9,32,11,30);
array<char*,2> b(2,"Hello","Welcome");
int I;
a[3]=600;
for(i=0;i<10;i++) cout << a[i] << " ";
cout<<endl;
for(i=2;i<4;i++) cout << b[i] << " ";
}
template<class T>
void demo<T>::show()
{ Output
cout<<data<<endl; 45
} Hello
-1.07374e+008
template<class T>
class derive : public demo<T>
{
};
Digitech Technologies 177
IO Streams
Streams hide the details of what happens to the data inside the
actual I/O devices.
Reads
Source Stream Program
Writes
istream ostream
iostream
#include<stdio.h>
#include<iostream.h>
void main()
{
printf("%x %d\n",65,70);
cout.setf(ios::hex);
cout<<65<<" "; Output
cout.unsetf(ios::hex); 41 70
cout.setf(ios::dec); 41 70
cout<<70<<endl;
}
Digitech Technologies 182
IO Streams
#include<stdio.h>
#include<iostream.h>
void main()
{
printf("*%-4d*\n*%10d*\n",65,70);
cout<<'*';
cout.width(4);
cout.setf(ios::left);
cout<<65<<'*'<<endl;
cout<<'*'; Output
cout.width(10); *65 *
cout.setf(ios::right); * 70*
cout.unsetf(ios::left); *65 *
cout<<70<<'*'<<endl;
* 70*
}
Digitech Technologies 183
IO Streams
#include<iostream.h>
void main()
{
cout.width(4);
cout.setf(ios::left);
cout.fill('*');
cout<<65<<endl;
cout.width(10);
cout.setf(ios::right);
Output
cout.unsetf(ios::left);
65**
cout.fill('-');
--------70
cout<<70<<endl;
}
Digitech Technologies 184
IO Streams
#include<iostream.h> #include<iostream.h>
cout<<s<<endl; cout<<s<<endl;
} }
Output Output
Enter name : Ravi Kumar Enter name : Ravi Kumar
Ravi Ravi Kumar
#include<iostream.h>
void main()
{
char s1[80],s2[80];
#include<iostream.h>
void main()
{
char s[80];
cout<<s<<endl;
}
ostream& operator<<(int);
ostream& operator<<(unsigned int);
ostream& operator<<(char);
ostream& operator<<(unsigned char);
ostream& operator<<(char*);
ostream& operator<<(float);
:
#include<iostream.h>
class employee
{
char name[20];
int sal;
friend istream& operator>>(istream &,employee &);
friend ostream& operator<<(ostream &,employee &);
};
void main()
{
employee e;
cin>>e; Output
cout<<e;
} Enter name : Ravi Kumar
Enter sal : 9000
Ravi Kumar --- 9000
cin customization
#include<iostream.h>
istream& operator>>(istream &a,void *b)
{
cout<<(char*)b;
return a;
}
void main()
{
int a,b;
File Streams
ofstream
ofstream()
ofstream(char *fname,int mode=ios::out)
open(char *fname,int mode=ios::out)
close();
long tellp()
seekp(long position,int seek_direction=ios::beg)
fstream
fstream()
fstream(char *fname,int mode)
open(char *fname,int mode) ...
Digitech Technologies 194
IO Streams
#include<fstream.h>
void main()
{
char name[20];
int sal;
ofstream x(“emp.dat”,ios::app);
if( x.bad() ) { cout << ”error\n”; return 1; }
x << name << ’,’ << sal << endl;
}
Digitech Technologies 196
IO Streams
#include<fstream.h>
void main()
{
char name[20];
int sal;
ifstream x(“emp.dat”);
if( x.bad() ) { cout << ”error\n”; return 1; }
while( !x.eof() )
{
x.getline(name,20,’,’);
x >> sal;
if( x.good() ) cout << name << ” ----- “ << sal;
}
x.close();
}
Digitech Technologies 197
IO Streams
void main()
{
record r;
cout << ”Enter emp name “; cin.getline(r.name,23);
cout << ”Enter salary “; cin >> r.sal;
ofstream x(“empr.dat”,ios::app);
if( x.bad() ) { cout << ”error\n”; return 1; }
x.write( (char*)&r,sizeof( r ));
}
Digitech Technologies 198
IO Streams
void main()
{
record r;
int rec,max;
ifstream x(“empr.dat”);
if( x.bad() ) { cout << ”error\n”; return 1; }
x.seekg(0,ios::end);
max=x.tellg()/sizeof( r );
Digitech Technologies 199
IO Streams
rec=1;
while( rec>0 )
{
cout << ”enter a record number 1 to “ << max << ” : “;
cin >> rec;
cin.get();
if(rec>=1 && rec<=max)
{
x.seekg( (rec-1)*sizeof( r ),ios::beg );
x.read( (char*)&r,sizeof( r ) );
cout << r.name << ” ---- “ << r.sal << endl;
}
else cout << ”invalid record number\n”;
}
x.close();
}
Digitech Technologies 200
IO Streams
Manipulators
Manipulators are objects that can be used within the chain of
insertion and extraction operators. Manipulators are used to set
stream attributes from within the chain of << or >> operators.
#include<iostream.h> Output
41
void main() 70
{
cout << hex << 65 << endl << dec << 70 << endl;
}
Digitech Technologies 201
IO Streams
Method Manipulator
--------------------------------------------
setf(long) setiosflags(long)
unsetf(long) resetiosflags(long)
width(int) setw(int)
fill(char) setfill(char)
---------------------------------------------
#include<iostream.h>
#include<iomanip.h>
void main()
{
cout << setw(10) << setiosflags(ios::left) << setfill('*')
<< 65 << endl
<< setw(20) << resetiosflags( ios::left )
<< setiosflags(ios::right) << setfill('-') << 65 << endl;
}
Output
65********
------------------65
User-Defined Manipulator
#include<iostream.h>
class set
{
public:
int w,j;
char f;
set(int a,int b,char c):w(a),j(b),f(c){}
};
a.setf(ios::right);
a.unsetf(ios::left);
}
else
{
a.setf(ios::left);
a.unsetf(ios::right);
}
return a;
}
void main()
{
cout << set(10,0,'*') << 65 << endl Output
<< set(20,1,'-') << 65 << endl; 65********
} ------------------65
#include<iostream.h>
class demo
{
int num;
int rc;
public:
demo():num(0),rc(0){}
demo(int k):num(k),rc(0){}
void show(){ cout<<num<<'-'<<rc<<endl; }
void addReference(){ rc++; }
int removeReference()
{
if(rc>0) rc--;
return rc;
}
};
Digitech Technologies 208
Smart Pointers( Simple Example )
typeid Operator
typeid( type-id )
or
typeid( expression )
type_info Class
class type_info {
public:
virtual ~type_info();
int operator==(const type_info& rhs) const;
int operator!=(const type_info& rhs) const;
const char* name() const;
const char* raw_name() const;
private: ...};
Digitech Technologies 211
RTTI - Run-Time Type Identification
void main()
{
employee *e=new manager;
Output
manager
Digitech Technologies 213
Standard Template Library ( STL )
STL Components
• Containers:
used to manage collections of objects of a certain kind
ex: vector, queue, list
• Algorithms:
functions for processing the elements of a container
ex: function to copy, sort and search container
• Iterators:
are used to step through the elements of containers
ex: iterator to move through a list
STL Containers
- Sequential containers:
- Associative containers:
STL Containers
set/multiset
vector
Map/multimap
deque
list
Digitech Technologies 217
Standard Template Library ( STL )
void main()
{
vector<int> v;
int i;
for(i=0;i<v.size();i++)
cout << v[i] << " ";
v.at(2)=88;
Digitech Technologies 218
Standard Template Library ( STL )
vector<int>::iterator it=v.begin();
cout<<endl;
for(i=0;i<v.size();i++) cout << it[i] << " ";
it=it+2;
Output
v.erase( it );
45 59 22 78 14
45 59 88 78 14
cout<<endl;
45 59 88 78 14
for(i=0;i<v.size();i++)
45 59 78 14
cout << v.at(i) << " ";
cout<<endl;
}
Digitech Technologies 219
Standard Template Library ( STL )
d.push_front(78); d.push_front(14);
for(i=0;i<d.size();i++)
Output
cout << d[i] << " ";
14 78 45 59 22
cout<<endl;
}
Digitech Technologies 220
Standard Template Library ( STL )
list<int>::iterator it=l.begin();
for(int i=0;i<l.size();i++)
{
cout<<*it<<" ";
it++;
}
Digitech Technologies 221
Standard Template Library ( STL )
cout<<endl;
}
/*
Output
78 45 59 22 14
78 45 59 22 14
*/
- Set:
A set is a collection where elements are sorted according to
their own values
- Multiset:
A multiset is the same as set except that duplicates are
allowed
- Map:
A map contains elements that are key/value pairs. Elements
are sorted on keys. Each key may occur only once.
- Multimap:
A multimap is the same as map, except that duplicates are
allowed ( multiple elements may have the same key
Digitech Technologies 223
Standard Template Library ( STL )
set<int>::iterator it=s.begin();
for(i=0;i<s.size();i++)
{ cout<<*it<<" ";
it++; Output
} 14 22 45 59 78
cout<<endl; }
Digitech Technologies 224
Standard Template Library ( STL )
s.insert(employee("Ravi",6700));
s.insert(employee("Giri",8900));
s.insert(employee("Sham",4500));
s.insert(employee("Ganesh",2200));
s.insert(employee("Kiran",7700));
set<employee>::iterator it=s.begin();
for(i=0;i<s.size();i++) Output
{ Ganesh 2200
it->show(); Giri 8900
it++; Kiran 7700
} Ravi 6700
} Sham 4500
Digitech Technologies 226
Standard Template Library ( STL )
m.insert( pair<int,int>(1,10) );
m.insert( pair<int,int>(2,20) ); Output
m.insert( pair<int,int>(0,30) );
m.insert( pair<int,int>(3,40) ); 30 10 20 40 50
m.insert( pair<int,int>(4,50) );
sort(n,n+10);
for(int i=0;i<10;i++)
cout<<n[i]<<" ";
cout<<endl;
}
/*
Output
12 34 36 44 44 56 78 78 90 95
*/
Digitech Technologies 228
Standard Template Library ( STL )
void main()
{
int n[10]={56,44,78,90,34,12,36,78,95,44};
int *p=find(n,n+10,34);
cout<<"Position:"<<p-n<<" Value:"<<*p<<endl;
}
/*
Output
Position:4 Value:34
*/
Digitech Technologies 229
Standard Template Library ( STL )
Function Objects
void main()
{
int n[10]={56,44,78,90,34,12,36,78,95,44};
int i;
Digitech Technologies 231
Standard Template Library ( STL )
sort(n,n+10,abc());
for(i=0;i<10;i++) cout<<n[i]<<" ";
cout<<endl;
abc t;
sort(n,n+10,t);
for(i=0;i<10;i++) cout<<n[i]<<" ";
cout<<endl;
}
Output
12 34 36 44 44 56 78 78 90 95
95 90 78 78 56 44 44 36 34 12
95 90 78 78 56 44 44 36 34 12
Digitech Technologies 232