You are on page 1of 232

Object Oriented Concepts

Course Objective

To introduce the principles and concepts behind Object Oriented


Programming

To explain how complex scenarios can be handled easily using


Object Oriented Technology

To learn good OO design practices

Digitech Technologies 1
Object Oriented Concepts

Limitations of Structured Programming

Modules are tightly coupled

Scope of reusability is limited

As the code size grows, maintaining code becomes difficult

Any major changes required to functionality later may result in


a lot of changes in code

Digitech Technologies 2
Object Oriented Concepts

What is an Object ?

An object
Is an unique, identifiable, self-contained entity that
contains attributes and behaviors.

Is modeled after real world objects


Can be viewed as a "black box" which receives and sends
messages

Examples
Car ,Telephone , Pen etc

Digitech Technologies 3
Object Oriented Concepts

State and Behavior

Example: Car object Example: Dog Object


State State
Current Speed Color
Current Gear Breed
Engine State (Running, Behavior
Not Running) Barking
Behavior (Acts on the object Wag Tail
and changes state) Eat
Slow down
Accelerate
Stop
Switch Off Engine
Start Engine

Digitech Technologies 4
Object Oriented Concepts

Abstraction
The process of forming general and relevant concepts from a
more complex scenario

Helps simplify the understanding and using of any complex system

Hide information that is not relevant

Simplifies by comparing to something similar in real world

Example: one doesn’t have to understand how the engine works


to drive a car

Engine Driving
Digitech Technologies 5
Object Oriented Concepts

Abstraction Example (Making of a Computer chip)

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

Encapsulate = “En” + “Capsulate”

“En” = “In a”
Encapsulate = “In a Capsule”

Encapsulation means localization of information of knowledge


within an object.
Encapsulation also means “Information hiding”

Example: A car’s dashboard hides the complexity and internal


workings of its engine.

Digitech Technologies 7
Object Oriented Concepts

Encapsulation (Data hiding)

Process of hiding the members from outside the class

Implemented using the concept of access specifiers

public,
private etc.

Typically in a class

State is private (not accessible externally)

Behavior is public (accessible externally)

Digitech Technologies 8
Object Oriented Concepts

Relationships

Different types of relationships can exist between classes

There are 3 types of relationships

Is-A (or Kind-Of)


Has-A (or Part-Of)
Uses-A

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

features or properties from another class +GetCustomerID() : int


+SetDuration()
+SetLoanAmount()
+SetInterestRate()
+SetCustomerID()

Inheritance allows definition of new classes on


similar lines of a base class (Also called Housing Loan
-InterestType : char
+GetInterestType() : char
parent or Super class) +SetInterestType()

Inherits
The class which inherits from another
class is called as ‘derived class’ Wealth

Digitech Technologies 10
Object Oriented Concepts
Loan

Multi-Level Inheritance -LoanAmount : double


-InterestRate : float
-Duration : int
-CustomerID : int
A class can inherit from another class +GetInterestRate() : float
+GetLoanAmount() : double
Data required
for all types
+GetDuration() : int loans
+GetCustomerID() : int
Derived class inherits all the members +SetDuration()
+SetLoanAmount()
of base class +SetInterestRate()
+SetCustomerID()

Another class can inherit from the


BusinessLoan
derived class -InterestType : char
Data additionally
-Term : char
required for
+GetInterestType() : char BusinessLoan.
+SetInterestType()
The new class inherits all the member +GetTerm() : char
Common
members inherited
+SetTerm() from base class
of all its ancestor classes
LargeBusinessLoan Special type of
-MoratoriumPeriod : int BusinessLoan.
+GetMoratoriumPeriod() : int Has some more
+SetMoratoriumPeriod() additional
members

Digitech Technologies 11
Object Oriented Concepts

Multiple Inheritance

Concept of a class inheriting from


more than one base class

Example: A Hybrid car can inherit


from FuelCar and BatteryCar

FuelCar ElectricCar
-TankCapacity : float -BatteryCapacity : float
-TypeOfFuel : char

HybridCar

Digitech Technologies 12
Object Oriented Concepts

Advantages and Disadvantages of inheritance

Advantages

Promotes reusability

Helps in better abstraction, thereby resulting in better design

Eliminates duplication of code

Disadvantages

Overuse of this concept (in cases where not necessary) leads


to bad design

Wrong usage of inheritance can lead to code and design


complexity
Digitech Technologies 13
Object Oriented Concepts

Has-A Relationship - Aggregation

class HousingLoan has ‘PropertyDetails’ as a member variable

class PropertyDetails has ‘Address’ as a member variable

Address is a generic class which can store any address


(address of a property or address of a person etc)
HousingLoan
Address
-CustomerID : int
-AddressLine1 : char
-Duration : int
-AddressLine2 : string
-InterestRate : float PropertyDetails -City : string
-LoanAmount : double
-PropertyHolderName : string -Zip : string
-TypeOfInterest : char
-Address : Address -State : string
-PropertyDetails : PropertyDetails Has A Has A
-DocumentNumber : int +GetAddressLine1() : string
+GetInterestRate() : float
+GetDocumentNumber() : int +SetAddressLine1()
+SetInterestRate()
+SetDocumentNumber() +GetAddressLine2() : string
+GetLoanAmount() : double
+GetProperyHolderName() : string +SetAddressLine2()
+SetLoanAmount()
Part of +SetPropertyHolderName() Part of +GetCity() : string
+GetCustomerID() : int
+GetAddress() : Address +SetCity()
+SetCustomerID()
+SetAddress() +GetZip() : string
+GetDuration() : int
+SetZip()
+SetDuration()
+GetState() : string
+GetTypeOfInterest() : char
+SetState()
+SetTypeOfInterest()

Digitech Technologies 14
Object Oriented Concepts

Message Passing

An object by itself may not be very useful

Useful work happens when one object invokes methods on other


objects

Example:

A car by itself is not capable of any activity

A person interacts with the car using steering


wheel, gauges on dashboard and various pedals

This interaction between objects result in


‘change of state’ achieving something useful
Digitech Technologies 15
Object Oriented Concepts

Polymorphism

Refers to an object’s ability to behave differently depending on


its type

Poly = ‘many’
morph = ‘form’

This characteristic enables making extensions to a class’s


functionality

Two features of an object which achieve polymorphism

Method Overloading (or Function overloading)

Method Overriding (or Function overriding)


Digitech Technologies 16
Object Oriented Concepts

What is a Class ?

A Class

Is a blue print used to create objects.

Is a software template that defines the methods and


variables to be included in a particular kind of Object.

Examples :

Animal, Human being, Automobiles,


Bank Account, Customer

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

•Functions defined inside 5


Current
Seating Speed
the class form the Capacity 45 km/h
State is internal to
7 the object. Not
(STATE)
behavior of class Number
of Doors
exposed to external
world/other objects

) w
Ch

wn lo
4

Do e (S
an

•Exposed to external world


ge

ak
G

Br
ea
r

Digitech Technologies 18
Object Oriented Concepts

Example: Objects and Classes

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

Practice of using same method name to denote several different


operations

Some OO languages allow overloading of both functions and


Operators (like +, - etc)

Example:

Consider a String class which is a utility class designed to


abstract and simplify string operations

‘Append’ functions are overloaded to accept different types of


data

Digitech Technologies 20
Object Oriented Concepts

Method Overriding

Refers to the practice of providing a different implementation of


a method in the derived class

Method in derived class may be completely different from the


implementation in the base class

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

Method Overriding - Examples

Shape Abstract class Loan


(Does not implement -LoanAmount : double
+Draw() Draw function) -InterestRate : float
-Duration : int
-CustomerID : int
+GetInterestRate() : float
+GetLoanAmount() : double
+GetDuration() : int
Line Rectangle Circle Octagon +GetCustomerID() : int
+SetDuration()
-... -... -... -... +SetLoanAmount()
+Draw() +Draw() +Draw() +Draw() +SetInterestRate()
+SetCustomerID() Simple
+Report() Loan
Report

Housing Loan
-InterestType : char
+GetInterestType() : char
+SetInterestType() Housing
+Report() Loan
Report

Digitech Technologies 22
Structured Programming (Procedure-Oriented)

• The structured programming paradigm is:

– Decide which procedure you want


– Use the best algorithm you can find

• Here the focus is on the algorithm required to perform the


desired computation

• Complexity hiding is also one of the objectives in structured


programming

• In this style of programming, importance is given to procedure


(logic) and not to the data on which these procedures
operateCourse Objective
Digitech Technologies 23
Limitations of Structured Programming

• Modules are tightly coupled

• Scope of reusability is limited

• As the code size grows, maintaining code becomes difficult

• Any major changes required to functionality later may result in


a lot of changes in code

Digitech Technologies 24
Procedural versus Object Oriented Programming

• In procedural programming, functions operate based on either


local or global data
• In Object oriented programming, Objects interact with other
objects by passing message

Digitech Technologies 25
Object Oriented Concepts

• Abstraction: Process of forming of general and relevant concept


from more complex scenarios.

• Encapsulation: Localization of information within an object.


This also leads to Information Hiding

• Inheritance: Is a process by which one object acquires the


properties of another object

• Polymorphism: Is a characteristic of OO Programming which


allows one interface to control access to a general class of actions.
The specific action is determined by the exact nature of the
situation.

Digitech Technologies 26
Basics of C++

• C++ is an Object Oriented programming language

• It can be considered as a super set of C

• This enables backward compatibility

• Bjarne Stroustrup first invented “C with Classes” and then it


was renamed to C++ in 1983.

•In 1997, ANSI/ISO standards committee standardized C++

•Like C, C++ is also case sensitive.


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

C++ is backward compatible with C


C Style comments are also supported
C Style comments are used to write function headers ,
file headers etc

Example:
/****************************************************
* This style of commenting is used for functions and files
*****************************************************/

C++ style of comments are single line comments


Any text after // is comment till the end of the line

Example:
// This is for single line comment
fArea = fRadius * fRadius * PI ; // calculating area of Circle
Digitech Technologies 31
Control Structures

Control Structures are statements which changes the execution


sequence of the program

C++ supports all the control structures supported in C

– If, else if, else

– switch case

– for loop

– while loop

– do while

Digitech Technologies 32
C and C++ differences

In C the main function can be made recursive, but not in C++.

In C++ the variables can be declared any where.


The advantage is a variable can be declared near its use.

In C new structure variables are created using


struct struct_name var_list;
In C++ the struct keyword is not required.
struct_tag itself serves as type name.
struct_name var_list;

Scope resolution operator (::)


a) Unary form: ::object
refers to an object of global scope.
b) Binary form: class_name::member
defines a member that belongs class_name
Digitech Technologies 33
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;

::printf("%d %d %d\n",printf , a , ::a );

::cout<<cout<<endl;
}

Digitech Technologies 34
C and C++ differences

In C++ a constant variable must be initialized but not in C.

All standard library functions must have prototypes in C++.

C++ supports C type-cast syntax and also got a new syntax

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

C++ constants are of two types

Logical constant

Logical constants are internally handled as macros.


A Logical constant does not exist in memory. A const declaration
is taken as logical constant if the initial value is known.

Physical constant

Physical constants are provided sufficient memory space.


A const declaration is taken as physical constant if the initial value
is given at run-time.

Digitech Technologies 36
C and C++ differences

efault arguments

++ function formal parameters can be initialized. Such formal


arameters are known as default arguments.

he default values are assumed by the function if the required


ctual parameters are missing in the function call.

ules for setting the default arguments

After a default argument the remaining arguments must have


default values.

Default arguments must be set either in the function prototype


or in the function definition, which ever occurs first.

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

#include<iostream.h> int main()


{
int max(int a,int b) int n1=55,n2=90;
{ float f1=67.55,f2=22.22;
return a > b ? a : b; char c1='p',c2='a';
}
cout << max(n1,n2) <<endl;
char max(char a,char b) cout << max(f1,f2) <<endl;
{ cout << max(c1,c2) <<endl;
return a > b ? a : b; return 0;
} }
Output
float max(float a,float b) 90
{ 67.55
return a > b ? a : b; p
}

Digitech Technologies 39
C and C++ differences

Reference variables

A Reference variable is another name given to an existing variable.


Reference variables use the memory given to the existing variable.

syntax: data_type &ref_var=var;

#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>

void swap(int *a,int *b) void swap(int &a,int &b)


{ {
int t=*a; int t=a;
*a=*b; a=b;
*b=t; b=t;
} }

void main() void main()


{ {
int x=10,y=20; int x=10,y=20;
swap(&x,&y); swap(x,y);
cout << x << " " << y cout << x << " " << y
<< endl; << endl;
} }
Output Output
20 10 20 10

Digitech Technologies 41
C and C++ differences

Returning reference to a variable

#include<iostream.h>

int& abc(int &a)


{
return a;
}

int main()
{
int x=90;
cout << x << endl; Output
abc(x)=300;
90
cout << x << endl;
return 0;
300
}

Digitech Technologies 42
Objects

The real or virtual world is made of objects. The objects exist in


some relationship with other objects.

A programming language should enable programmers to create


objects that behave like real world objects.

Software Objects define an abstract representation of real or


virtual world entities in order to simulate them.

Objects encapsulate a portion of knowledge in a problem domain


or the world in which they evolve.

Digitech Technologies 43
Objects

Definitions

An atomic entity composed of state, behavior.

An Object is a region of storage with associated semantics.

An Object is an instance of a data type.

An object is a self-contained entity that can maintain its state.

Digitech Technologies 44
Objects

State

The state groups the values of all the attributes of an object at


a given time, where an attribute is a piece of information.

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

from data members can also

as methods.

e behavior to the object.

ng ‘.’ or ‘->’ operators.

sending message to the object.

et_time();

ere as
ass type.

Digitech Technologies 46
Abstraction

A class or a structure should hide (protect) its data members


and expose its operations to outside world.

C++ members can be protected or exposed to others by using


access specifier.

C++ access specifiers

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

Access specifiers specify the scope of the access permitted on a


member variable or a member function

public: Can be accessed within the class or from outside of the class

private: Can be accessed only within the class

protected: Same like private but accessible in derived class

Data members in a class should always be private

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

class is same as struct except the default access specifier.

In struct the default access specifier is public.

In class the default access specifier is private

struct student class student


{ {
char name[20]; char name[20];
int age; int age;
: :
}s; }s;

void main() void main()


{ {
s.age=20; // legal s.age=20; // illegal
Digitech Technologies 49
Objects

An instance of a class in memory

In a program, there can be many instances of a class


(Many objects of same class)

If class can be viewed as a type, then object is a variable of


that type

Examples:

Trainee is a class. “Arun” is an Object of Trainee class

Educator is a class. “Rajagopal” is an Object of Educator class

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.

But an object that is just created may contain illegal values.

So there must be some way to initialize a newly create object.


class student void main()
{ {
char name[20]; student s;
int age;
public: cout << s.getAge()<<endl;
int getAge() }
{
return age; Output
} -858993460
};
Digitech Technologies 51
Constructor

Constructors are special member functions and have the same


name as the class itself.

A constructor implicitly gets called when an object of that type


is created.

Constructors have no return value ( not even void ).

Constructors can be overloaded.

A constructor without arguments is called default constructor and


a constructor with arguments is called overload constructor.

If a class does not have any constructor , then C++ adds default
constructor without any statements in it.

Digitech Technologies 52
Constructor

#include<iostream.h> void main()


#include<string.h> {
student s("Ravi Kumar",20);
class student s.show();
{ }
char name[20];
int age;
public:
student()
{
age=18;
strcpy(name,"unknown"); Output
} Ravi Kumar 20
student(char *a,int b)
{
age=b;
strcpy(name,a);
}
void show() { cout << name << " " << age << endl; }
};

Digitech Technologies 53
Destructor

Like constructors being invoked at the time of creation,


a destructor is invoked when an object is destroyed

Destructors will have the same name as the class preceded


by a tilde(~)

• No arguments
• No return value
• Cannot be overloaded

Used for housekeeping job for recovering the memory allocated

class employee
{
:
~employee()
{
}
Digitech Technologies 54
Named and anonymous objects

Named object declaration syntax

class_name var;
// implicitly calls default constructor

class_name var(value1,..);
// implicitly calls overloaded constructor

Unnamed (Anonymous) objects syntax

class_name();
// unnamed default object

class_name(v1,v2);
// unnamed initialized object

Digitech Technologies 55
Anonymous Object

#include<iostream.h> int main()


#include<string.h> {
person p1("ramesh");
class person p1.display();
{ {
char name[20]; person t("Kiran");
public: p1=t;
person(){ name[0]=0; } }
p1.display();
person(char *a) return 0;
{ } int main()
strcpy(name,a); {
} person p1("ramesh");
p1.display();
void display() {
{ p1=person("Kiran");
cout << name << endl; }
} p1.display();
return 0;
void setName(char *a) { strcpy(name,a); } }
};
Digitech Technologies 56
Representing a class in UML Class Diagrams

UML Class Diagram Representation of Exployee Class

Notations in UML Emplopyee


-name : char[20]
‘+’ before a member indicates ‘public’ -age : int
#total_marks : int
‘-’ before a member indicates ‘private’
+Employee(char*,int,int)
‘#’ before a member indicates ‘protected) +getName*() : char*
+getAge() : int
+getTotalMarks() : int
-calculate() : int

Digitech Technologies 57
Constant data members

Constant data member

An object may have some fixed properties. Such properties remain


unchanged throughout the life of the object.

Fixed properties can be created using ‘const’ type qualifier.

A constant data member can be initialized with the help of a


constructor.

class class_name
{
class_name( ... ) : mem1(val1),mem2(val2) ...
{
}
:
};
Digitech Technologies 58
Constant member functions

Methods are of two types

Accessor methods
Accessor methods can not modify the active object state.

Accessor method can be created by declaring the method as


constant.

data_type function_name(…) const


{
:
}

Mutator methods
Mutator methods can modify the active object state.

Digitech Technologies 59
Constant members

#include<iostream.h> int main()


#include<string.h> {
Employee e("Rajesh",1001,8900);
class Employee e.show();
{ e.setSal(10000);
const int empid; e.show();
int sal; return 0;
char name[20]; }
public:
Employee(char *a,int b,int c) : empid(b) , sal(c)
{
strcpy(name,a); Output
} 1001 Rajesh 8900
void show() const 1001 Rajesh 10000
{
cout << empid << " " << name << " " << sal << endl;
//sal=1000;
}
void setSal( int a ) { sal=a; }
};

Digitech Technologies 60
Object property types

Objects may have three different types of properties

Individual object property


A copy of ordinary data member is given to every
instance of the class. Different instances of the class may
have different content

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

A static data member is used to provide shared property for


the objects of the same class type.

A single copy exists for all instances of the class type.

All static data members must be defined in the global space.


( only in C++ )

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

Provide a very generic functionality that doesn’t require us to


instantiate the class.

Can be called using the class name.

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

#include<iostream.h> int main()


{
class car car a,b,c,d;
{ cout << car::getcount() <<endl;
static int count; {
public: car e,f;
car(){ count++; } cout << car::getcount() <<endl;
~car(){ count--; } }
static int getcount() cout << car::getcount() <<endl;
{ return 0;
return count; } Output
4
}
6
}; 4

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

‘this’ pointer is a pointer that is automatically available in


all non-static member functions of a class.

It allows objects to access its own address

It points to the current object, the object that invoked the method.

When a member function is called, it is automatically passed an


implicit argument that is a pointer to the invoking object

Since static functions are not members of a class instance,


‘this’ pointer cannot be used with static member functions.

Digitech Technologies 66
this pointer

A class instance have a copy of data members but not member


functions.

All instances of a class share a single copy of member functions.


If this is the case then how a member function know which instance
it is supposed to be working on.

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’ pointer points to the object that is used to invoke the


member function. Within member function all member references
are changed to

this->member

Digitech Technologies 67
this pointer

The ‘this’ pointer can be used to differentiate between instance


variables and local variables in (which have same names) a
member function.
void main()
#include<iostream.h> {
class demo demo a(67);
{ int num; a.store(55);
public: a.display(); // 55
demo():num(0){} }
demo(int a):num(a){}
void display() { cout<<num<<endl; }
void store(int num)
{
this->num=num;
//demo::num=num;
}
};
Digitech Technologies 68
this pointer

#include<iostream.h> void main()


#include<string.h> {
radio a("Hyd"),b("Sec"),c("Mum"),d("Kol");
class radio b.send("Hello");
{ static int count; }
static radio *r[50];
char name[20]; output
public: from Hyd:Hello
radio(char *k) from Mum:Hello
{ strcpy(name,k); from Kol:Hello
r[count]=this;
count++;
}
void receive(char *k){ cout<<"from "<<name<<':'<<k<<endl; }
void send(char *k)
{ for(int i=0;i<count;i++)
if( this!=r[i] ) r[i]->receive(k);
}
}; Write a program to create some radio stations.
int radio::count=0; Show a message sent by a station is received by all
radio * radio::r[50]; other stations.
Digitech Technologies 69
Different ways of class implementation

#include<iostream.h> #include<iostream.h>

class demo class demo


{ {
int num; int num;
public: public:
demo():num(0){} demo();
demo(int a):num(a){} demo(int);
void show() void show();
{ };
cout<<num<<endl;
} demo::demo():num(0){}
};
demo::demo(int a):num(a){}

void main() void demo::show()


{ {
demo a,b(45); cout<<num<<endl;
a.show(); }
b.show();
}

Digitech Technologies 70
Coding standards and naming conventions

Class names should start with capital letter


- Account, Employee, Date

Member variables should have 'm_' prefix followed by


Hungarian notation
class Date
{
private:
int m_iDay;
int m_iMonth;
int m_iYear;
char m_acDayOfWeek[10];
};

Instance of classes should typically have a prefix 'o'


- Date oToday, oTomorrow;

Digitech Technologies 71
Coding standards and naming conventions

Names of functions:

- prefix 'fn' only for C-Style functions which don't belong


to any class

- Names of Member functions should start with capital letter


followed by capital letter for every subsequent word.

class Date
{
private:
//Data members
public:
short GetDayOfMonth ();
char* GetDateOfWeek ();
};

Digitech Technologies 72
Coding standards and naming conventions

There are two steps to create a class


– A class is declared in a header file (.h file)
Only one class should be declared in a single header file

– A corresponding .cpp file must have the implementation


of the class
The body of methods are defined #ifndef _EMPLOYEE_H
#define _EMPLOYEE_H
The class should be declared within the // Class definition here
#ifndef _FILENAME_H #endif // _EMPLOYEE_H
:
#endif block
– Avoids double inclusion of same header even if included twice

– The block between the #ifndef and #endif is expanded only


if the header has not been included already

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 or Method Header block:

All functions (or methods) in the C++ files should be preceded


by a comment block in the format given below:

/*********************************************************
* 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();

//Method to get the Employee name


char* GetEmployeeName();

//method to set the Employee number


void SetEmployeeNumber(int iEmpNum);

//Method to set the Employee name


void SetEmployeeName(char* pcEmpName);
};

#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
*****************************************************/

void Employee::SetEmployeeName(char* pcEmpName)


{
strcpy(m_acEmpName,pcEmpName);
}

/*****************************************************
* 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

Aggregation refers to a relationship where one class contains


objects of another class as it’s members

Aggregation leads to Has-A relationship

Digitech Technologies 82
C++ Dynamic Allocation Operators

The new and delete operators are used to allocate and free
memory at run time.

The new operator allocates memory and returns a pointer to the


start of it.

The delete operator frees memory previously allocated using new.

The general forms of new and delete are shown here:


p_var = new type;
delete p_var;
Here, p_var is a pointer variable that receives a pointer to memory
that is large enough to hold an item of type type.

Use malloc/realloc to allocate memory for the simple variables

Use new for allocating memory for the objects


Digitech Technologies 83
C++ Dynamic Allocation Operators

• The dynamic memory allocation happens on the heap.

• Heap is a memory space which grows or shrinks dynamically.

• Whenever the memory is allocated dynamically for any object,


a space is allocated in the heap. This allocation remains until it is
deleted (freed).

• 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

• Never use new/delete operators in case of the simple variables;


Instead use malloc and free

• All the memory allocations that happen within the class needs to
be deallocated within the destructor.

• All the object pointers allocated dynamic memory must be


deleted when not required.

Digitech Technologies 85
String class

#include<iostream.h> void copy(char *a)


#include<string.h> { delete s;
s=new char[ strlen(a)+1 ];
class str strcpy(s,a);
{ }
char *s; void add(char *a)
public: {
str() char *t
{ t=new char[ strlen(s)+strlen(a)+1 ];
s=new char[1]; strcpy(t,s);
*s=0; strcat(t,a); Output
} delete s;
str(char *a) s=t;
abc
{ } welcome xyz
s=new char[ strlen(a)+1 ]; };
strcpy(s,a); void main()
} {
void display() str a("hello"),b("welcome");
{ a.copy("abc"); b.add(" xyz");
cout<<s<<endl; a.display(); b.display();
} }

Digitech Technologies 86
Copy constructor

A built-in type variable can be initialized with one that is already


existing variable of the same type. This is also extended to user
defined types created using structures. In case of user defined
types, the initialization is done using member by member copy of
the structure data members.

In C++ the same is applicable to variables of class types.

The default member by member copy is not sufficient in case of a


class with pointer data members. The initialized object pointer
member and the existing object pointer member, both point to
same memory space. If the memory space is released with one of
the object pointer data member, then the other object pointer
member is invalid.

Digitech Technologies 87
Copy constructor

A copy constructor is automatically invoked when a new object


is initialized with an existing object of the same class type.

class_name::class_name( const class_name &var );

The parameter to copy constructor must be a reference of the same


type.

The copy constructor of a class is called when


1)An instance of a class created from an existing instance of
the same class.
2)A function is called and an argument of class type is
passed by value.

If a class does not have copy constructor, then C++ provides a


default copy constructor. The default copy constructor simply
uses memberwise copying.
Digitech Technologies 88
Copy constructor
#include<iostream.h> #include<iostream.h>
#include<string.h> #include<string.h>
Output
class str class str
{ { Hello
char *s; char *s; Hello
public: public:
: :
void abc( str k ) void abc( str k )
{ {
strcpy(k.s,”aaa”); strcpy(k.s,”aaa”);
} }
}; str( str &m )
Output {
void main() Hello s=new char[ strlen(m.s)+1];
{ aaa strcpy(s,m.s);
str a,b(“Hello”); }
b.display(); };
a.abc(b);
b.display(); void main(){ same as before }
}

Digitech Technologies 89
Inline Functions

We can create short functions that are not actually called;


rather, their code is expanded in line at the point of each invocation.

This is process is somewhat similar to using a function-like macro.

To make a function inline, prefix the function definition with inline

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

A friend function is a non-member function that is granted


permission to access private members.

A class may grant friendship

•to a global function

•to another class

•to a particular member function of another class

Digitech Technologies 91
Friend Functions

Global friend function


int sum2(demo x,demo y)
#include<iostream.h> {
return x.num+y.num;
class demo
}
{
int num;
public: void main()
demo():num(0){} {
demo(int a):num(a){} demo a(5),b(7);
cout<<a.sum1(b) <<endl;
int sum1(demo x) cout<<sum3(a,b) <<endl;
{ }
return num+x.num;
/* output
}
12
friend int sum2(demo,demo); 12
}; */

Digitech Technologies 92
Friend Class

#include<iostream.h> void main()


{
class demo abc a;
{ a.show();
int num; a.display();
public: }
demo():num(0){}
demo(int a):num(a){} /* Output
friend class abc;
45
};
45
class abc */
{
public:
void show() { demo k(45); cout << k.num << endl; }
void display() { demo k(45); cout << k.num << endl; }
};

Digitech Technologies 93
Friend Functions

#include<iostream.h> void abc::show()


{
class abc demo k(45);
{ cout << k.num << endl;
public: }
void show();
void display(); void abc::display()
}; {
demo k(45);
class demo //cout << k.num << endl;
{ }
int num;
public: void main()
demo():num(0){} {
demo(int a):num(a){} abc a;
friend void abc::show(); a.show();
}; a.display();
}

Digitech Technologies 94
Operator overloading

Consider the following messages on a string object.

str a; str a;
a.copy(“Hello”); a=“Hello”;
a.add(“Abc”); a+“Abc”;

Using = and + is easy to remember and more readable than


the function names like copy and add.

But C++ operators cannot operate on user defined types.

Operator overloading is a process of providing a user defined


behavior to an operator on user defined data_type.

The overloaded operators behavior remains unchanged on other


data types.

Digitech Technologies 95
Operator overloading

Operator overloading rules

1) Only existing operators can be overloaded.

2) The operators . :: sizeof .* and ?: cannot be overloaded.

3) The overloaded operators priority and associativity cannot


be changed.

4) Operators can be overloaded only on user defined types.

Digitech Technologies 96
Operator overloading

An operator is overloaded by providing a special function called


‘operator’.

When the compiler see an operator on user defined type, it will


search and map the statement to the special function operator
provided for the operator and the operand types.

Syntax:
data_type operator opr_char( [ data_type p1 ] [, data_type p2 ] )
{
}

Digitech Technologies 97
Operator overloading

Operators can be overloaded as member functions and also


as global functions.

To be a member function, the first operand in the expression must


be of the class type.

The first operand is used as active object to call the method.

The other operand if exists will become formal parameter to


the method.

A global operator overloading is most likely made a friend function


to a class. This is in order to gain access on private members
of the class.

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 (…)

Ellipsis enables a function have variable number of arguments


( like with printf and scanf functions ).
data_type function_name( … )
{
}
Ellipsis can be accessed using va_list, va_start and va_arg defined
in stdarg.h header file.

First create a variable of va_list type


va_list k;

After creating the list variable, the list need initalized using
va_start( va_list , the last known parameter name )

To extract elements from ellipsis use


data_type va_arg( va_list , data_type )
Each call to va_arg returns the next element from ellipsis.
Digitech Technologies 101
Ellipsis (…)

#include<iostream.h>
#include<stdarg.h>

void abc(int m,...)


{ va_list k;
va_start(k,m);
cout<<endl;
for(int i=0;i<m;i++) cout << va_arg(k,int) << " ";
}
Output
void main() 44 55 66
{ 67 44
abc(3,44,55,66);
abc(2,67,44); 23 77 55 48 34
abc(0);
abc(5,23,77,55,48,34);
}
Digitech Technologies 102
Operator overloading
#include<iostream.h>
#include<stdarg.h>
#include<stdlib.h> void main()
{
class array array a(10,56,7,89,45,33,8,9,32,11,30);
{
int *n,max;
a[3]=600;
public:
for(int i=0;i<10;i++) cout << a[i] << “ “;
array(int a,...) : max(a)
}
{
va_list x;
va_start(x,a);
n=new int[max];
for(int i=0;i<max;i++) n[i]=va_arg(x,int);
}
int& operator[](int a)
{
if(a<0 || a>=max ) { cout<<“error in index”<<endl; exit(1); }
return n[a];
}
};
Digitech Technologies 103
Operator overloading
Simulation of **, the power operator

#include<iostream.h> void main()


{
class Number Number a(5),b(3);
{ cout<<a*b<<endl<<a**b<<endl;
int num; }
public:
Number():num(0){} /*
Number(int a):num(a){} Output
int operator*(Number &a) 15
{ 125
return num*a.num; */
}
Number* operator*() { return this; }
int operator*(Number *a)
{
int i,n=1;
for(i=0;i<a->num;i++) n = n * num ;
return n;
}
};
Digitech Technologies 104
Type Conversions

Example for Built-in type to User-defined type conversion


#include<iostream.h>
#include<string.h>
class demo
{
int num;
public:
demo():num(0){}
demo(int a):num(a){}
demo(char *k) { num = strlen(k); }
void display() { cout<<num<<endl; }
};
Output
void main() 90
{ demo a,b(23),c=b,d=45; 23
a=90; 23
a.display(); b.display(); c.display(); d.display(); 45
a=”Hello”; 5
a.display();
}
Digitech Technologies 105
Type Conversions

Example for User-defined to Built-in type conversion

#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 process of deriving a new class from an existing class is


called Inheritance

• The old class is referred to as the base class and the new class is
called the derived class or subclass.

• Through Inheritance, C++ strongly supports the idea of


Reusability. That is making use of the existing features to
create the new feature.

• All the objects in this world come under some kind of classification.
Inheritance allows the creation of hierarchical classification.

• For example, the bike “Yamaha” is a part of the class


‘Two Wheeler’ which is again a part of the class ‘Vehicle’.

Digitech Technologies 108


Inheritance

Digitech Technologies 109


Inheritance

Generalization and Specialization

• Generalization and Specialization are associated with the


concept of Inheritance

• The Trainee class derives the Employee class

• Employee class is a generalization of Trainee class

• Trainee class is a specialization of the Employee class

Digitech Technologies 110


Inheritance

Inheritance Relationship

• “is a” relation exists between the derived class


and base class.

• Trainee is an Employee
Employee

Trainee

Digitech Technologies 111


Inheritance

Creating derived classes

• The general format of deriving the properties from one class


to another class is :

class derived-class-name : [visibility-mode] base-classname [,…]


{
// members of derived class
};

• Here, the visibility mode is optional and , if present, may be


either private , public or protected.

• The default visibility mode is private.

• Visibility mode specifies whether the features of the base class


are privately derived or publicly derived.
Digitech Technologies 112
Inheritance

Types of Inheritance based on structure

Digitech Technologies 113


Inheritance
Derivation types Derivation Base class Access in
type member derived class
Derivation type Private private (inaccessible)
determines the base
members accesibility public private
in the derived class
protected private

Public private (inaccessible)

public public

protected protected

Protected private (inaccessible)

public protected

protected protected

Digitech Technologies 114


Inheritance

Protected Members

• The ‘private’ members cannot be accessed outside the scope


of the class.

• The derived class also cannot access the private members.

• Sometimes, we want the derived class to access the private


members of the base class but at the same time, we don’t want
to access those members thru the object of the class.

• Those members come under protected access specifier.

• In other words, protected members are private to all, but public


to its derived classes.

Digitech Technologies 115


Inheritance

Protected Members

Advantages:

• Derived classes can modify values directly


• Slight increase in performance; Avoids set/get function
call overhead

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

Constructors in the Base and Derived Classes

An instance of a derived class contains the data members inherited from


its base class and its own data members. To initialize the members,
compiler first calls the base class constructor to initialize base class
members, and then calls derived class constructor to initialize the derived
class members.

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:

derive_class( a1,a2,a3,… ) : base_class( p1,p2,… ) , mem_init


{
}

If base class parameter list is not provided, then compiler automatically


calls the base class default constructor.

Digitech Technologies 117


Inheritance
#include<iostream.h>

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; } }
};

class derive : public base


/* output
{ 22
int num; 45
public: */
derive():num(0){}
derive(int k):base(k/2),num(k){}
void display()
{ cout<<num<<endl; }
};

Digitech Technologies 118


Inheritance

ethod Overriding

Providing different implementation in the derived class for the


methods defined in the Base class is called as Method Overriding.

The method signatures must be same.

In such cases where the derived class objects invoke the


overridden methods, the derived class overridden methods are
invoked.

Digitech Technologies 119


Inheritance
#include<iostream.h>

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; } }
};

class derive : public base


/* output
{ 22
int num; 45
public: */
derive():num(0){}
derive(int k):base(k/2),num(k){}
void show()
{ cout<<num<<endl; }
};

Digitech Technologies 120


Inheritance
Point2D and Point3D ( without inheritance )
#include<iostream.h> class threeD
{
class twoD twoD td;
{ int z;
int x,y; public:
public: threeD():z(0){}
twoD():x(0),y(0){} threeD(int a,int b,int c):z(c)
twoD(int a,int b):x(a),y(b){} {
void display() td.setx(a); td.sety(b);
{ }
cout << x << " " << y << " "; void display()
} {
void setx(int a){ x=a; } td.display();
void sety(int a){ y=a; } cout << z << " ";
}; }
void main()
void setx(int a){ td.setx(a); }
{
void sety(int a){ td.sety(a); }
threeD td(56,34,90);
void setz(int a){ z=a; }
td.display(); cout<<endl;
};
td.setx(51);
td.display();
}
Digitech Technologies 121
Inheritance
Point2D and Point3D ( with inheritance )
#include<iostream.h> class threeD : public twoD
{
class twoD int z;
{ public:
int x,y; threeD():z(0) { }
public: threeD(int a,int b,int c):
twoD():x(0),y(0){} twoD(a,b),z(c){}
twoD(int a,int b):x(a),y(b){}
void display() void display()
{ {
cout << x << " " << y << " "; twoD::display();
} cout << z << " ";
void setx(int a){ x=a; } }
void sety(int a){ y=a; } void setz(int a){ z=a; }
}; };
void main()
{
threeD td(56,34,90);
td.display(); cout<<endl;
td.setx(51);
td.display();
}
Digitech Technologies 122
Inheritance

Assignment Operator overloading for a Derived Class

Like Copy Constructor of derived class that explicitly calls


Copy Constructor of base class, assignment operator overloading
of derived class must explicitly call base class assignment
operator function.

derive derive::operator=(int a)
{
base::operator=(a); // calling base assignment operator overloading
:
:
}

Digitech Technologies 123


Inheritance

Copy Constructors of Base and Derived Classes

When a new instance of derived class created using derive class


copy constructor, the Compiler does not automatically call the
base class copy constructor. Instead of the base class
copy constructor, the compiler calls default constructor of
the base class.

This problem can be overcome by an explicit call to base class


copy constructor from derive class copy constructor.

Digitech Technologies 124


Inheritance

#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>

class common_base virtual inheritance


{
int x;
public:
common_base():x(0){}
common_base(int a):x(a){}
void show() { cout<<x<<endl; }
};

class base1 : virtual public common_base


{
int x;
public:
base1():x(0){}
base1(int a):x(a){}
void show() { cout<<x<<endl; }
};

Digitech Technologies 127


Inheritance

class base2 : virtual public common_base


{
int x; virtual inheritance
public:
base2():x(0){}
base2(int a):x(a){}
void show() { cout<<x<<endl; }
};

class derive : public base1,public base2


{
int x;
public:
derive():x(0){} void main()
derive(int a):common_base(a), {
base1(a),base2(a),x(a){} derive d(25);
void show() d.show();
{ d.common_base::show();
cout<<x<<endl; d.base1::show();
} d.base2::show();
}; }

Digitech Technologies 128


Inheritance - Example

#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

class manager : public employee


{
int sal;

public:

manager(){}
manager(char *a,int b):employee(a,’A’),sal(b){}
void display()
{
employee::display();
cout<<sal<<” “;
}
int pay()
{
return sal;
}
};

Digitech Technologies 130


Inheritance - Example

class wage_employee : public employee


{
int hours,rate;

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){}
};

Digitech Technologies 131


Inheritance - Example

class sales_person : public wage_employee


{
int comm,sales;
public:
sales_person(){}
sales_person(char *a,int b,int c,int d,int e):wage_employee(a,b,c,’B’),
comm(d),sales(e){}
void display()
{
wage_employee::display();
cout<<comm<<” “<<sales<<” “;
}
int pay()
{
return wage_employee::pay()+( sales>100 ? comm : 0 );
}
};

Digitech Technologies 132


Inheritance - Example

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=='w' || ch=='s' || ch=='m')


{
cout<<"Enter name ";
cin.getline(name,20);
Digitech Technologies 133
Inheritance - Example

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++;
}
}
}
}

Digitech Technologies 135


Inheritance - Example

int i; long wsum=0;


for(i=0;i<wmax;i++)
long msum=0; {
for(i=0;i<mmax;i++) w[i].display();
{ cout<<w[i].pay()<<endl;
m[i].display(); wsum=wsum+w[i].pay();
cout<<m[i].pay()<<endl; }
msum=msum+m[i].pay();
} cout<<msum+ssum+wsum
<<endl;
long ssum=0; }
for(i=0;i<smax;i++) /* end of main */
{
s[i].display(); The for loops are identical
cout<<s[i].pay()<<endl;
except the object references
ssum=ssum+s[i].pay();
}
This is because the data is
stored in three different arrays

Digitech Technologies 136


Inheritance - Example

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=='w' || ch=='s' || ch=='m')


{
cout<<"Enter name ";
cin.getline(name,20);

Digitech Technologies 137


Inheritance - Example

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++;
}
}
}
}

Digitech Technologies 139


Inheritance - Example

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
}

Digitech Technologies 140


Polymorphism

• Is a Greek word, which means one name, multiple forms.

• Is the ability of objects to respond differently to the same message.


The kind of response is dependent on the data types used in a
given instance.

• Allows objects having different internal structure to share the same


external interface.

Digitech Technologies 141


Polymorphism

Polymorphism - Binding

• Binding refers to the process of linking a procedure call to the


code to be executed in response of the call.

• Are of two types.


– Static binding or Early binding and
– Dynamic binding or Late binding.

• In Static binding the code associated with a given procedure call


is resolved during compiler time.

• In Dynamic binding the code associated with a given procedure


call is resolved during run-time.

Digitech Technologies 142


Polymorphism

#include<iostream.h>
#include<string.h>

class employee ...


class manager : public employee …
class wage_employee : public employee ...
class sales_person : public wage_employee ...

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

Digitech Technologies 143


Polymorphism

#include<iostream.h>
#include<string.h>

class employee {… virtual void display(){ … } ...


class manager : public employee …
class wage_employee : public employee ...
class sales_person : public wage_employee ...

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

Digitech Technologies 144


Polymorphism

Virtual functions—Dynamic Polymorphism

• 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();

• The base class pointers can now be pointing to derived types

employee *e=new sales_person(…);


e->display();

• This actually invokes the sales_person class method

• This determination of which version of the overridden method to


invoke happens at run time. This is known as Dynamic Binding
Digitech Technologies 145
Polymorphism

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;
}

Digitech Technologies 146


Polymorphism

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

• At times we may not want the objects of the base class to be


created at all

• If one of the methods of the base class is made pure virtual


function then that class will become abstract.

Example:
virtual int pay()=0;

• No objects of abstract class can be created.

• But pointers to abstract class can be created

• Abstract classes act like an interface.

Digitech Technologies 149


Polymorphism

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

class rectangle : public shape


{ Shape Example
int h,w;
public:
rectangle(int a,int b):h(a),w(b){}
int area() { return h*w; }
};
void main()
{
shape *s[]={ new circle(5), new rectangle(6,10),
new rectangle(12,4), new square(5),
new circle(15), new circle(6),
new circle(19), new square(16),
new square(25) };
long sum=0;
int max = sizeof(s) / sizeof(s[0]) ;
for(int i=0;i<max; i++) sum=sum+s[i]->area();
cout << sum <<endl;
}
Digitech Technologies 153
Polymorphism

General purpose sort Example

#include<iostream.h> class sort


#include<string.h> {
public:
class sortable static void bubble(sortable **e,int max)
{ {
public: sortable *t;
virtual int compare(sortable*)=0; 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];
Any user-defined types can e[k]=e[k+1];
be sorted using the sort e[k+1]=t;
class, provided the class }
}
defines ‘compare’ method.
};

Digitech Technologies 154


Polymorphism
class employee : public sortable General purpose sort Example
{
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(sortable *k)
{
employee *e=(employee *)k;
return sal-e->sal;
}
};

Digitech Technologies 155


Polymorphism
#define MAX 5 General purpose sort Example
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) };

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

Digitech Technologies 156


Polymorphism

#include<iostream.h> Virtual Destructor

class base
{
public:
~base(){ cout<<"from base destructor\n"; }
};
class derive : public base
{
public:
~derive(){ cout<<"from derive destructor\n"; }
};

void main() Output


{ from base destructor
base *d=new derive();
delete d;
}
Digitech Technologies 157
Polymorphism

#include<iostream.h> Virtual Destructor

class base
{
public:
virtual ~base(){ cout<<"from base destructor\n"; }
};
class derive : public base
{
public:
~derive(){ cout<<"from derive destructor\n"; }
};

void main() Output


{ from derive destructor
base *d=new derive(); from base destructor
delete d;
}
Digitech Technologies 158
Exception Handling

• An Exceptional condition is an event that occurs during the


execution of C++ program (runtime anomalies) causing a
program to interrupt.

Examples:
Out-of-bound array subscript, arithmetic overflow or underflow,
division by zero, out of memory, invalid function parameter, etc.,

• An exceptional condition may be either an unexpected error or


an expected error at an unpredictable time.

Digitech Technologies 159


Exception Handling

• The process of detecting and taking an appropriate action for


exceptions is referred to exception handling.

• Exception handling involves the following steps.


(1) Find the error (try),
(2) Inform that an error as occurred (throw),
(3) Receive the error information (catch) &
(4) Take corrective actions (Handle)

• The C++ exception handling mechanism is built upon three


keywords namely try, throw and catch.

Digitech Technologies 160


Exception Handling

• The keyword try is used to preface a block of statements which


may generate exceptions. This block of statements is known as
try block.

• The throw statement is used to inform that an exception has


occurred. It is coded within the try block.

• The keyword catch is used to preface a block called catch block


to receive and handle the exception informed by the throw
statement.

• The catch block must immediately follow the try block that
throws the exception.

Digitech Technologies 161


Exception Handling

Syntax for try and catch blocks

:
try
{
:
if( … ) throw exception;
:
}
catch (type argument)
{
:
}
:

Digitech Technologies 162


Exception Handling

• When the try block throws an exception, the program control


leaves the try block and enters the catch block.

• If the type of the object thrown matches the argument type in


the catch statement, then the catch block is executed otherwise
the program is aborted with the help of the abort ( ) function.

• If no exception is thrown, the control goes to the statement


immediately following the catch block.

Digitech Technologies 163


Exception Handling
#include<iostream.h>
Simple example
int abc(int x,int y)
{
if(y==0) throw "/ by 0 error";
return x/y;
}
void main()
{
int a,b,c;
cout<<"Enter two numbers ";
cin>>a>>b;
try
{
c=abc(a,b);
cout<<c<<endl;
}
catch(char *e)
{
cout<<e<<endl;
}
}
Digitech Technologies 164
Exception Handling
#include<iostream.h>
Raising exception from within try block
int abc(int x,int y) and from outside try block
{
if(y==0) throw "/ by 0 error";
return x/y;
}

void main()
{
int a,b,c;
char ch;

try
{
while( 5 )
{
cout<<"Enter two numbers ";
cin>>a>>b;
try
{

Digitech Technologies 165


Exception Handling
c=abc(a,b);
cout<<c<<endl; Raising exception from within try block
} and from outside try block
catch(char *e)
{
cout<<e<<endl;
}

cout<<"\ntry more (y/n) ";


cin>>ch;
cin.get();

if(ch=='n' || ch=='N') throw -1;


}
}
catch(...) // default handler
{
cout<<"\ntry next time...";
}
}

Digitech Technologies 166


Exception Handling

• It is possible to have multiple catch blocks following a try block


to handle all possible exceptions.

• In some situations, we may not be able to anticipate all possible


types of exceptions. In such cases we can catch all exceptions
using the following form of catch statement.

Syntax to catch all types of exceptions

catch(…) // catch with ellipsis


{
:
}

Digitech Technologies 167


Templates

• Is mechanism provided to implement the concept of


generic programming.

• Allows programmers to create a family of similar


classes or functions.

• Eliminate code duplication for different types and thus make the
software development easier and more manageable.

• Are to be defined with parameters that would be replaced by a


specified data type at the time of actual use of the
class or function.

Digitech Technologies 168


Templates

Templates are example code for compiler, which generates actual


code with the help of the template.

Templates are of two types

Function templates: Function templates are also known as


parameterized or generic functions.
Class templates: Class templates are also known as parameterized
or generic types.

Function Template syntax:


template< class T [ , class M , ..... ] >
data_type function_name( data_type var1, ... )
{
data_type v1,v2; // local variables
}
Digitech Technologies 169
Templates
#include<iostream.h>
#include<string.h> Function Template Example
template< class T >
T max( T x, T y )
{
return x>y ? x : y;
}

char* max( char *x, char *y )


{
if( strlen(x)>strlen(y) ) return x; else return y; Output
} 20
void main()
x
{ 88.34
int a=10,b=20; welcome
char c=’x’,d=’h’;
float e=56.99,f=88.34;
char s1[20]=”welcome”,s2[20]=”hello”;
cout << max(a,b) << endl << max(c,d) << endl
<< max(e,f) << endl << max(s1,s2) << endl;
}
Digitech Technologies 170
Templates
#include<iostream.h>
template<class T> Class Template Example
class demo
{
T data;
public:
demo(){}
demo(T a):data(a){}
void display()
{
cout << data << endl; Output
}
};
67
void main() hello
{ -1.07374e+008
demo<int> a(67);
demo<char*> b(“hello”);
demo<float> c;

a.display(); b.display(); c.display();


}
Digitech Technologies 171
Templates

General Purpose Sorting Template Function

#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;
}
}

Digitech Technologies 172


Templates

General Purpose Sorting Template Function

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;
}
};

Digitech Technologies 173


Templates

General Purpose Sorting Template Function

#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

Digitech Technologies 174


Templates

Class Template : Array Example

#include<iostream.h>
#include<stdarg.h>
#include<stdlib.h>

template<class T,int s>


class array
{
T *n;
int max;
public:
array(int a,...) : max(a)
{
va_list x;
va_start(x,a);

n=new T[max];
for(int i=0;i<max;i++) n[i]=va_arg(x,T);
}

Digitech Technologies 175


Templates

Class Template : Array Example

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] << " ";
}

Digitech Technologies 176


Templates
#include<iostream.h> void main()
{
template<class T> demo<int> a(45);
class demo demo<char*> b("Hello");
{ demo<float> c;
T data;
public: a.show();
demo(){} b.show();
demo(T k):data(k){} c.show();
void show(); }
};

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 are channels of communication between programs and


source/destination of data

A stream is either a source of bytes or a destination for bytes.

Provide a good abstraction between the source and destination

Abstract away the details of the communication path from


I/O operation

Streams hide the details of what happens to the data inside the
actual I/O devices.

Streams can read/write data from/to blocks of memory, files etc...

Digitech Technologies 178


IO Streams

Reads
Source Stream Program

Writes

Program Stream Destination

Digitech Technologies 179


IO Streams

The stream classes are defined in ‘iostream.h and fstream.h’


header files.

The stream classes are of two types. Console streams and


File streams.
ios

istream ostream

iostream

ifstream fstream ofstream

Digitech Technologies 180


IO Streams

A stream property can be set by using formatting flags.


Formatting flags are enums defined in ‘ios’ class.
The formatting flags are

ios::dec output number format is decimal


ios::oct output number format is octal
ios::hex output number format is hexadecimal
ios::uppercase hexadecimal alphabets ( a-f ) in uppercase

ios::left left adjust data in a field width


ios::right right adjust data in a field width

ios::showpos ‘+’ prefixed to a positive value


ios::showbase prefix the base indicator
no_prefix --- decimal ex: 65
0 prefix --- octal ex: 065
0x prefix --- hexadecimal ex: 0x65
Digitech Technologies 181
IO Streams

Methods for setting/resetting formatting flags


setf(long flag) sets specified flag without affected other flags
unsetf(long flag) resets specified flag without affected other flags

#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

Method for setting field width


width(int) :the width set is valid only for the next argument printed.

#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

Method for setting padding character : fill(char)


padding character is a character used to fill unused spaces in a

#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

Unformatted input methods


char get()
get() is same as ‘getchar’ function in ‘C’

get(char *dest, int max, char termination =’\n’)


gets input from buffer and stores at ‘dest’. The characters input
is either max or upto the termination character.

getline(char *dest, int max, char=’\n’)


getline() is same as get(...) except it extracts data from buffer
including the termination character.

read(char *dest, int max)


read() gets max characters from input buffer. It does not have
any termination character.
Digitech Technologies 185
IO Streams

#include<iostream.h> #include<iostream.h>

void main() void main()


{ {
char s[80]; char s[80];

cout<<"Enter name : "; cout<<"Enter name : ";


cin>>s; cin.get(s,80);

cout<<s<<endl; cout<<s<<endl;
} }

Output Output
Enter name : Ravi Kumar Enter name : Ravi Kumar
Ravi Ravi Kumar

Digitech Technologies 186


IO Streams

#include<iostream.h>

void main()
{
char s1[80],s2[80];

cout<<"Enter name : ";


//cin.get(s1,80);
//cin.get();
cin.getline(s1,80);

cout<<"Enter name : "; Output


cin.get(s2,80); Enter name : ravi
Enter name : giri
ravi
cout<<s1<<endl<<s2<<endl;
giri
}

Digitech Technologies 187


IO Streams

Read method is used to read a random access file

#include<iostream.h>

void main()
{
char s[80];

cout<<"Enter name : ";


cin.read(s,80);

cout<<s<<endl;
}

Digitech Technologies 188


IO Streams
Formatted input methods
The formatted input methods are ‘>>’ operator overloading providedin istream class.
istream& operator>>(int&);
istream& operator>>(unsigned int&);
istream& operator>>(char&);
istream& operator>>(unsigned char&);
istream& operator>>(char*);
istream& operator>>(float&);
:
Formatted output methods
The formatted output methods are the ‘<<’ operator overloading provided in
ostream class.

ostream& operator<<(int);
ostream& operator<<(unsigned int);
ostream& operator<<(char);
ostream& operator<<(unsigned char);
ostream& operator<<(char*);
ostream& operator<<(float);
:

Digitech Technologies 189


IO Streams

Customizating cin and cout objects

#include<iostream.h>

class employee
{
char name[20];
int sal;
friend istream& operator>>(istream &,employee &);
friend ostream& operator<<(ostream &,employee &);
};

istream& operator>>(istream &k,employee &m)


{
cout<<"Enter name : ";
cin.getline(m.name,20);
cout<<"Enter sal : ";
cin>>m.sal;
return k;
}
Digitech Technologies 190
IO Streams

Customizating cin and cout objects

ostream& operator<<(ostream &k,employee &m)


{
cout<<m.name<<" --- "<<m.sal<<endl;
return k;
}

void main()
{
employee e;

cin>>e; Output
cout<<e;
} Enter name : Ravi Kumar
Enter sal : 9000
Ravi Kumar --- 9000

Digitech Technologies 191


IO Streams

cin customization

#include<iostream.h>
istream& operator>>(istream &a,void *b)
{
cout<<(char*)b;
return a;
}

void main()
{
int a,b;

cin >> (void*)”Enter a number “ >> a


>>(void*)”ENTER A NUMBER “ >> b;
cout << a+b << endl;
}
Digitech Technologies 192
IO Streams

File Streams

Sequential access file :

In sequential file records can only be read sequentially.


To read records randomly, the address of Nth record should known.
Sequential file record size varies, that is why the address of Nth
record can not be found.

Random access file :

In random access files records can be read randomly.


Random records size is fixed, that is why address of Nth record
can be found.
( rec_number - 1 ) * ( size of record )

Digitech Technologies 193


IO Streams

File stream classes are defined in fstream.h header file.


Ifstream
ifstream()
ifstream(char *fname,int mode=ios::in)
open(char *fname,int mode=ios::in)
close();
long tellg()
seekg(long position,int seek_direction=ios::beg) ad )

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

File Open Modes


ios::in file opened to input
ios::out file opened to output
ios::app file opened to append records

File Seek Direction


ios::beg set file pointer from beginning of the file
ios::cur set file pointer from current position of the file
ios::end set file pointer from end of the file

File Status Methods


int good() returns true value if the last operations successful
int bad() returns true value if last operation failed
int eof() returns true value if end of file is reached

Digitech Technologies 195


IO Streams

Appends a record to emps.dat sequential file

#include<fstream.h>
void main()
{
char name[20];
int sal;

cout << ”Enter emp name “;


cin.getline(name,20);
cout << ”Enter salary “;
cin >> sal;

ofstream x(“emp.dat”,ios::app);
if( x.bad() ) { cout << ”error\n”; return 1; }
x << name << ’,’ << sal << endl;
}
Digitech Technologies 196
IO Streams

Reads records from emps.dat and prints them on screen

#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

Appends a record to empr.dat random file


#include<fstream.h>
struct record
{
char name[23];
int sal;
};

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

Reads records randomly


#include<fstream.h>
struct record
{
char name[23];
int sal;
};

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.

Manipulators are of two types


Built-in manipulators without arguments
dec - sets output format to decimal
oct - sets output format to octal
hex - sets output format to hexadecimal
endl - generates newline sequence

#include<iostream.h> Output
41
void main() 70
{
cout << hex << 65 << endl << dec << 70 << endl;
}
Digitech Technologies 201
IO Streams

Built-in manipulators with single argument

Method Manipulator
--------------------------------------------
setf(long) setiosflags(long)
unsetf(long) resetiosflags(long)
width(int) setw(int)
fill(char) setfill(char)
---------------------------------------------

The single argument manipulators are defined in ‘iomanip.h’


header file.

Digitech Technologies 202


IO Streams

#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

Digitech Technologies 203


IO Streams

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){}
};

ostream& operator<<( ostream &a,set b )


{
a.width( b.w );
a.fill( b.f );
if( b.j )
{
Digitech Technologies 204
IO Streams

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

Digitech Technologies 205


Smart Pointers

•Take care of automatic initialization and cleanup

•Take care of dangling pointers

•Keep track of dynamically allocated objects shared by


multiple owners

Digitech Technologies 206


Smart Pointers

void abc() void abc()


{ {
demo *p(new demo); auto_ptr<demo> *p(new demo);
p->doSomething(); p->doSomething();
delete p; }
}

void abc() void abc()


{ {
demo *p; auto_ptr<demo> p(new demo);
try try
{ {
p=new demo; p->doSomething();
p->doSomething(); }
delete p; catch(…){…}
}
catch(…){…}
Digitech Technologies 207
Smart Pointers( Simple Example )

#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 )

class RCPtr void main()


{ demo *pointee; {
public: RCPtr t(new demo(56));
RCPtr(demo *t):pointee(t) t->show();
{ pointee->addReference(); (*t).show();
} }
RCPtr(const RCPtr &t):pointee(t.pointee)
{
pointee->addReference();
}
~RCPtr()
{
if( pointee->removeReference()==0 ) delete pointee;
}
demo* operator->(){ return pointee; }
demo& operator*(){ return *pointee; } Output
}; 56-1
56-1
Digitech Technologies 209
RTTI - Run-Time Type Identification

•Knowing the type of identifiers at run-time

•typeid(expr.) is used to know the type of expression at run-time

typeid Operator
typeid( type-id )
or
typeid( expression )

•The typeid operator allows the type of an object to be determined


at run-time.

•The result of a typeid expression is a const type_info&.

The value is a reference to a type_info object that represents


either the type-id or the type of the expression, depending on
which form of typeid is used.
Digitech Technologies 210
RTTI - Run-Time Type Identification

type_info Class

The type_info class describes type information generated within


the program by the compiler. Objects of this class effectively store
a pointer to a name for the type. The type_info class also stores
an encoded value suitable for comparing two types for equality or
collating order. The encoding rules and collating sequence for
types are unspecified and may differ between programs.

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

#include<iostream.h> For RTTI make settings as shown:


#include<typeinfo.h> Project > Settings >
C/C++ tab >
class employee Category - C++ Language >
{ Check Run-Time Type information
public:
virtual void show()
{ cout<<"from employee\n"; }
};

class manager : public employee


{
public:
void show()
{ cout<<"from manager\n"; }
};

Digitech Technologies 212


RTTI - Run-Time Type Identification

class wage_employee : public employee


{
public:
void show()
{ cout<<"from wage_employee\n"; }
};

void main()
{
employee *e=new manager;

if( typeid(*e) == typeid(manager) )


cout << "manager" << endl;
}

Output

manager
Digitech Technologies 213
Standard Template Library ( STL )

The STL is a generic library that provides solutions to managing


of data with modern and efficient algorithms

Advantages of the STL

- You don’t have to write your classes and algorithms

- You don’t have to worry about allocating and freeing memory

- Reduces your code size because STL uses template

- Easy to use and easy to learn

Digitech Technologies 214


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

Digitech Technologies 215


Standard Template Library ( STL )

STL Containers

- Sequential containers:

are ordered collections in which each element has a certain


position
ex: vector, list, deque

- Associative containers:

are sorted collections in which the actual position of an


element depends on its value due to a certain sorting criterion
ex: set, map, multiset, multimap

Digitech Technologies 216


Standard Template Library ( STL )

STL Containers
set/multiset

vector

Map/multimap

deque

list
Digitech Technologies 217
Standard Template Library ( STL )

#include<iostream> vector example


#include<vector>

using namespace std;

void main()
{
vector<int> v;
int i;

v.push_back(45); v.push_back(59); v.push_back(22);


v.push_back(78); v.push_back(14);

for(i=0;i<v.size();i++)
cout << v[i] << " ";

v.at(2)=88;
Digitech Technologies 218
Standard Template Library ( STL )

cout<<endl; vector example


for(i=0;i<v.size();i++) cout << v[i] << " ";

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 )

#include<iostream> deque example


#include<deque>

using namespace std;


void main()
{
deque<int> d;
int i;

d.push_back(45); d.push_back(59); d.push_back(22);

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 )

#include<iostream> list example


#include<list>
using namespace std;
void main()
{
list<int> l;

l.push_back(45); l.push_back(59); l.push_back(22);


l.push_front(78); l.push_back(14);

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; list example


while( !l.empty() )
{
cout << l.front() << " ";
l.pop_front();
}

cout<<endl;
}

/*
Output
78 45 59 22 14
78 45 59 22 14
*/

Digitech Technologies 222


Standard Template Library ( STL )

STL - Associative Containers

- 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 )

#include<iostream> set example


#include<set>
using namespace std;
void main()
{
set<int> s;
int i;

s.insert(45); s.insert(59); s.insert(22);


s.insert(78); s.insert(14);

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 )

#include<iostream> set example


#include<string.h>
#include<set>
using namespace std;
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; }
bool operator<(const employee &e) const
{ //if(sal<e.sal) return true;
if( strcmp(name,e.name)<0) return true;
return false;
}
};
Digitech Technologies 225
Standard Template Library ( STL )

void main() set example


{ set<employee> s;
int i;

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 )

#include<iostream> map example


#include<map>
using namespace std;
void main()
{
map<int,int> m;
int i;

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) );

for(i=0;i<m.size();i++) cout<<m[i]<<" ";


cout<<endl;
}
Digitech Technologies 227
Standard Template Library ( STL )

#include<iostream> sort example


#include<algorithm>
using namespace std;
void main()
{
int n[10]={56,44,78,90,34,12,36,78,95,44};

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 )

#include<iostream> find example


#include<algorithm>

using namespace std;

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

- A function object encapsulates a function in an object for use by


other components.

- An object of any class or struct that overloads the function call


operator, operator()

Passing a function object to an algorithm is similar to passing a


pointer to a function, but there are some important differences

- pass function objects to algorithms at compile time

- increases efficiency, by inlining the corresponding call

Digitech Technologies 230


Standard Template Library ( STL )

#include<iostream> Function Object Example


#include<algorithm>

using namespace std;


class abc
{
public:
bool operator()(int x,int y) const
{
return x>y;
}
};

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); Function Object Example


for(i=0;i<10;i++) cout<<n[i]<<" ";
cout<<endl;

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

You might also like