+ All Categories
Home > Documents > object oriented concepts

object oriented concepts

Date post: 18-Nov-2014
Category:
Upload: jaykrishna
View: 443 times
Download: 5 times
Share this document with a friend
Description:
presentation was very nice , it is helpful to one and all
Popular Tags:
232
Digitech Technologies 1 Object Oriented Concepts Course Objective To introduce the principles and concepts behind Object Ori Programming To explain how complex scenarios can be handled easily usi Object Oriented Technology To learn good OO design practices
Transcript
Page 1: object oriented concepts

Digitech Technologies 1

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

Page 2: object oriented concepts

Digitech Technologies 2

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

Page 3: object oriented concepts

Digitech Technologies 3

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 objectsCan be viewed as a "black box" which receives and sends messages

ExamplesCar ,Telephone , Pen etc

Page 4: object oriented concepts

Digitech Technologies 4

Object Oriented Concepts

State and Behavior

Example: Car objectState

Current SpeedCurrent GearEngine State (Running, Not Running)

Behavior (Acts on the object and changes state)

Slow downAccelerateStopSwitch Off EngineStart Engine

Example: Dog ObjectState

ColorBreed

BehaviorBarkingWag TailEat

Page 5: object oriented concepts

Digitech Technologies 5

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

Page 6: object oriented concepts

Digitech Technologies 6

Object Oriented Concepts

Abstraction Example (Making of a Computer chip)

Diode

Capacitor

Resistor

Transistor

MOSFET

Basic ElectronicComponents

AND Gate

Inverter

Buffer

XOR Gate

OR Gate

Boolean Logic Gatesbuilt using basic

electronic components(1st Level abstraction)

A

H

Q1

Q8

ENB

Register

Digital circuits builtusing Boolean logic

gates(2nd Level abstraction)

U/D

Reset

B1

B8

Carry out

ENB

Binary Counter

Central Processing unit -Built using complex

digital circuits(3rd level abstraction)

Page 7: object oriented concepts

Digitech Technologies 7

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.

Page 8: object oriented concepts

Digitech Technologies 8

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)

Page 9: object oriented concepts

Digitech Technologies 9

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

Page 10: object oriented concepts

Digitech Technologies 10

Object Oriented Concepts

Is-A Relationship - Inheritance

Inheritance refers to a class replicating some

features or properties from another class

Inheritance allows definition of new classes on

similar lines of a base class (Also called

parent or Super class)

The class which inherits from another

class is called as ‘derived class’

Wealth

Inherits

+GetInterestRate() : float+GetLoanAmount() : double+GetDuration() : int+GetCustomerID() : int+SetDuration()+SetLoanAmount()+SetInterestRate()+SetCustomerID()

-LoanAmount : double-InterestRate : float-Duration : int-CustomerID : int

Loan

+GetInterestType() : char+SetInterestType()

-InterestType : charHousing Loan

Page 11: object oriented concepts

Digitech Technologies 11

Object Oriented Concepts

Multi-Level Inheritance

A class can inherit from another class

Derived class inherits all the membersof base class

Another class can inherit from the derived class

The new class inherits all the member of all its ancestor classes

+GetInterestRate() : float+GetLoanAmount() : double+GetDuration() : int+GetCustomerID() : int+SetDuration()+SetLoanAmount()+SetInterestRate()+SetCustomerID()

-LoanAmount : double-InterestRate : float-Duration : int-CustomerID : int

Loan

+GetInterestType() : char+SetInterestType()+GetTerm() : char+SetTerm()

-InterestType : char-Term : char

BusinessLoan

+GetMoratoriumPeriod() : int+SetMoratoriumPeriod()

-MoratoriumPeriod : intLargeBusinessLoan

Data requiredfor all types

loans

Data additionallyrequired forBusinessLoan.Commonmembers inheritedfrom base class

Special type ofBusinessLoan.Has some moreadditionalmembers

Page 12: object oriented concepts

Digitech Technologies 12

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

-TankCapacity : float-TypeOfFuel : char

FuelCar-BatteryCapacity : float

ElectricCar

HybridCar

Page 13: object oriented concepts

Digitech Technologies 13

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

Page 14: object oriented concepts

Digitech Technologies 14

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)

+GetInterestRate() : float+SetInterestRate()+GetLoanAmount() : double+SetLoanAmount()+GetCustomerID() : int+SetCustomerID()+GetDuration() : int+SetDuration()+GetTypeOfInterest() : char+SetTypeOfInterest()

-CustomerID : int-Duration : int-InterestRate : float-LoanAmount : double-TypeOfInterest : char-PropertyDetails : PropertyDetails

HousingLoan

+GetAddressLine1() : string+SetAddressLine1()+GetAddressLine2() : string+SetAddressLine2()+GetCity() : string+SetCity()+GetZip() : string+SetZip()+GetState() : string+SetState()

-AddressLine1 : char-AddressLine2 : string-City : string-Zip : string-State : string

Address

+GetDocumentNumber() : int+SetDocumentNumber()+GetProperyHolderName() : string+SetPropertyHolderName()+GetAddress() : Address+SetAddress()

-PropertyHolderName : string-Address : Address-DocumentNumber : int

PropertyDetails

Has A Has A

Part of Part of

Page 15: object oriented concepts

Digitech Technologies 15

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

Page 16: object oriented concepts

Digitech Technologies 16

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)

Page 17: object oriented concepts

Digitech Technologies 17

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

Page 18: object oriented concepts

Digitech Technologies 18

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 class

to external world

•Functions defined inside

the class form the

behavior of class

•Exposed to external world

45 km/h

CurrentSpeed

3

CurrentGear

5

Numberof Gears

7

SeatingCapacity

4

Numberof Doors

Accelerate

Brake

(Slo

w

Down)

Change Gear

(STATE)

(BEHAVIOR) Interface to externalworld (ThroughMethods/ Functionsonly)

State is internal tothe object. Notexposed to externalworld/other objects

Page 19: object oriented concepts

Digitech Technologies 19

Object Oriented Concepts

Example: Objects and Classes

Daria

R002

Jane

R003

Brittany

R004

Jodie

R001

classobject

Class Student

Name

Regn_No

setName()

setRegnNo()

CalcMarks()

Page 20: object oriented concepts

Digitech Technologies 20

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

Page 21: object oriented concepts

Digitech Technologies 21

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

Page 22: object oriented concepts

Digitech Technologies 22

Object Oriented Concepts

Method Overriding - Examples

+Draw()

Shape

+Draw()-...

Line

+Draw()-...Rectangle

+Draw()-...

Circle

+Draw()-...Octagon

Abstract class(Does not implement

Draw function)

+GetInterestRate() : float+GetLoanAmount() : double+GetDuration() : int+GetCustomerID() : int+SetDuration()+SetLoanAmount()+SetInterestRate()+SetCustomerID()+Report()

-LoanAmount : double-InterestRate : float-Duration : int-CustomerID : int

Loan

+GetInterestType() : char+SetInterestType()+Report()

-InterestType : charHousing Loan

SimpleLoanReport

HousingLoanReport

Page 23: object oriented concepts

Digitech Technologies 23

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

Page 24: object oriented concepts

Digitech Technologies 24

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

Page 25: object oriented concepts

Digitech Technologies 25

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

Page 26: object oriented concepts

Digitech Technologies 26

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.

Page 27: object oriented concepts

Digitech Technologies 27

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

C

Page 28: object oriented concepts

Digitech Technologies 28

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 extractionoperator.

cin and cout objects with >> and << are similar to scanf and printf

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

int main(){

printf("%d %c\n",65,65);cout<<65<<" "<<(char)65<<endl;

return 0;}

Output65 A65 A

Page 29: object oriented concepts

Digitech Technologies 29

cin and cout Basics

#include<iostream.h>

void main(){

int a,b;

cout<<"Enter two numbers ";cin>>a>>b;

if( cin.good() )cout << a+b << endl;

elsecout << "Invalid input\n";

cin.clear();}

outputEnter two numbers 45 HelloInvalid input

Enter two numbers 45 55100

Page 30: object oriented concepts

Digitech Technologies 30

Data types of C++

Page 31: object oriented concepts

Digitech Technologies 31

C++ comments

C++ is backward compatible with CC Style comments are also supportedC 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 commentsAny text after // is comment till the end of the line

Example:// This is for single line commentfArea = fRadius * fRadius * PI ; // calculating area of Circle

Page 32: object oriented concepts

Digitech Technologies 32

Control Structures

Control Structures are statements which changes the executionsequence of the program

C++ supports all the control structures supported in C

– If, else if, else

– switch case

– for loop

– while loop

– do while

Page 33: object oriented concepts

Digitech Technologies 33

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

Page 34: object oriented concepts

Digitech Technologies 34

C and C++ differences

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

int a=100;

void main(){

int a=45;int printf=78;int cout=55;

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

::cout<<cout<<endl;}

output78 45 10055

Page 35: object oriented concepts

Digitech Technologies 35

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(){ int a=300; char b; b=a; printf(“%d\n”,b); printf(“%d\n”,(char)a); printf(“%d\n”,char(a));}

Output444444

Page 36: object oriented concepts

Digitech Technologies 36

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.

Page 37: object oriented concepts

Digitech Technologies 37

C and C++ differences

Default arguments C++ function formal parameters can be initialized. Such formal parameters are known as default arguments.

The default values are assumed by the function if the required actual parameters are missing in the function call.

Rules 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.

Page 38: object oriented concepts

Digitech Technologies 38

C and C++ differences

Default arguments  #include<iostream.h> void abc(int=100,int=200); void main(){ abc(); abc(10); abc(10,20);}  void abc(int a,int b){ cout << a << " " << b <<endl;}

Output100 20010 20010 20

Page 39: object oriented concepts

Digitech Technologies 39

C and C++ differences

Function overloading

#include<iostream.h>

int max(int a,int b) { return a > b ? a : b; }

char max(char a,char b) { return a > b ? a : b; }

float max(float a,float b) { return a > b ? a : b; }

int main(){

int n1=55,n2=90;float f1=67.55,f2=22.22;char c1='p',c2='a';

cout << max(n1,n2) <<endl;cout << max(f1,f2) <<endl;cout << max(c1,c2) <<endl;return 0;

}Output9067.55p

Page 40: object oriented concepts

Digitech Technologies 40

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;

cout << &a << " " << &b <<endl; a=10; b=20; cout << a << " " << b << endl; }

output0x0012FF7C 0x0012FF7C20 20

Page 41: object oriented concepts

Digitech Technologies 41

C and C++ differences

#include<iostream.h>

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

int t=*a;*a=*b;*b=t;

}

void main(){

int x=10,y=20;swap(&x,&y);cout << x << " " << y

<< endl;}Output20 10

#include<iostream.h>

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

int t=a;a=b;b=t;

}

void main() {

int x=10,y=20;swap(x,y);cout << x << " " << y

<< endl; } Output 20 10

Page 42: object oriented concepts

Digitech Technologies 42

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;abc(x)=300;cout << x << endl;return 0;

}

Output90300

Page 43: object oriented concepts

Digitech Technologies 43

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.

Page 44: object oriented concepts

Digitech Technologies 44

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. 

Page 45: object oriented concepts

Digitech Technologies 45

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.

Page 46: object oriented concepts

Digitech Technologies 46

C++ struct and class

C++ structures and classes apart from data members can also have member functions.

The member functions are known as methods.

The methods are used to add some behavior to the object. The methods can be called by using ‘.’ or ‘->’ operators.

Calling a method is also known as sending message to the object.

a.set_time(); or b->set_time();

‘a’ is an object of a class type where as ‘b’ is a pointer to an object of a class type.

Page 47: object oriented concepts

Digitech Technologies 47

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.

Page 48: object oriented concepts

Digitech Technologies 48

Access specifiers in a class

Access specifiers specify the scope of the access permitted on amember 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 byother 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

Page 49: object oriented concepts

Digitech Technologies 49

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{ char name[20]; int age;

:}s;

void main(){ s.age=20; // legal

class student{ char name[20]; int age;

:}s;

void main(){ s.age=20; // illegal

Page 50: object oriented concepts

Digitech Technologies 50

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

Page 51: object oriented concepts

Digitech Technologies 51

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{ char name[20]; int age; public: int getAge() { return age; }};

void main(){ student s;

cout << s.getAge()<<endl;}

Output-858993460

Page 52: object oriented concepts

Digitech Technologies 52

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 defaultconstructor without any statements in it.

Page 53: object oriented concepts

Digitech Technologies 53

Constructor

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

class student{ char name[20]; int age; public: student() {

age=18; strcpy(name,"unknown");

} student(char *a,int b) { age=b;

strcpy(name,a); } void show() { cout << name << " " << age << endl; }};

void main(){

student s("Ravi Kumar",20);s.show();

}

OutputRavi Kumar 20

Page 54: object oriented concepts

Digitech Technologies 54

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

Page 55: object oriented concepts

Digitech Technologies 55

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

Page 56: object oriented concepts

Digitech Technologies 56

Anonymous Object

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

class person{ char name[20]; public: person(){ name[0]=0; }

person(char *a) {

strcpy(name,a); }

void display() {

cout << name << endl; }

void setName(char *a) { strcpy(name,a); }};

int main(){ person p1("ramesh"); p1.display(); {

person t("Kiran");p1=t;

} p1.display(); return 0;} int main()

{ person p1("ramesh"); p1.display(); {

p1=person("Kiran"); } p1.display(); return 0;}

Page 57: object oriented concepts

Digitech Technologies 57

Representing a class in UML Class Diagrams

UML Class Diagram Representation of Exployee Class

Notations in UML

‘+’ before a member indicates ‘public’

‘-’ before a member indicates ‘private’

‘#’ before a member indicates ‘protected)

Emplopyee

-name : char[20]

-age : int

#total_marks : int

+Employee(char*,int,int)

+getName*() : char*

+getAge() : int

+getTotalMarks() : int

-calculate() : int

Page 58: object oriented concepts

Digitech Technologies 58

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) ...{}:

};

Page 59: object oriented concepts

Digitech Technologies 59

Constant member functions

Methods are of two types

Accessor methodsAccessor methods can not modify the active object state.

Accessor method can be created by declaring the method asconstant.

data_type function_name(…) const{

:}

Mutator methodsMutator methods can modify the active object state.

Page 60: object oriented concepts

Digitech Technologies 60

Constant members

#include<iostream.h>#include<string.h> class Employee{

const int empid;int sal;char name[20];

  public:  Employee(char *a,int b,int c) : empid(b) , sal(c)

{strcpy(name,a);

}void show() const{

cout << empid << " " << name << " " << sal << endl; //sal=1000;

}void setSal( int a ) { sal=a; }

};   

int main(){ Employee e("Rajesh",1001,8900); e.show(); e.setSal(10000); e.show(); return 0;}

Output1001 Rajesh 89001001 Rajesh 10000

Page 61: object oriented concepts

Digitech Technologies 61

Object property types

Objects may have three different types of properties

Individual object propertyA copy of ordinary data member is given to every instance of the class. Different instances of the class mayhave different content

Fixed propertyA 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 propertyA single copy of the data member is created andit is used by all instances of the class type( static data members )

Page 62: object oriented concepts

Digitech Technologies 62

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{ static int num; int color; public: :};

Int demo::num=45;

Size of the class demo is four bytesbut not eight.

Size of a class is the sum of the sizes of non-static data members

Page 63: object oriented concepts

Digitech Technologies 63

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{ static int num; int color; public: demo(int a):color(a){} static int getNum() { return num; } int getColor(){ return color; }};Int demo::num=45;

void main(){ demo d(77),e(88); cout << d.getColor() << endl; cout << e.getColor() << endl; cout << demo::getNum();}

Page 64: object oriented concepts

Digitech Technologies 64

Static Members

#include<iostream.h>

class car

{

static int count;

public:

car(){ count++; }

~car(){ count--; }

static int getcount()

{

return count;

}

};

int main()

{

car a,b,c,d;

cout << car::getcount() <<endl;

{

car e,f;

cout << car::getcount() <<endl;

}

cout << car::getcount() <<endl;

return 0;

} Output464

Page 65: object oriented concepts

Digitech Technologies 65

Memory Allocation for Classes and Objects

Member functions are assigned common memory location to all objects

Data members are assigned seperate memory locations for seperate objects

GetEmployeeNumber(); GetEmployeeName(); SetEmployeeNumber(int); SetEmployeeName(char*)

m_iEmpNum; char* m_pcEmpName

m_iEmpNum; char* m_pcEmpName

m_iEmpNum; char* m_pcEmpName

EmployeeOne

EmployeeTwo

EmployeeThree

Page 66: object oriented concepts

Digitech Technologies 66

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.

Page 67: object oriented concepts

Digitech Technologies 67

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

Page 68: object oriented concepts

Digitech Technologies 68

this pointer

The ‘this’ pointer can be used to differentiate between instance variables and local variables in (which have same names) a member function.

#include<iostream.h>class demo{ int num;

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

this->num=num; //demo::num=num;

}};

void main(){ demo a(67); a.store(55); a.display(); // 55}

Page 69: object oriented concepts

Digitech Technologies 69

this pointer

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

class radio{ static int count;

static radio *r[50];char name[20];

public:radio(char *k){ strcpy(name,k);

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

};int radio::count=0;radio * radio::r[50];

void main(){

radio a("Hyd"),b("Sec"),c("Mum"),d("Kol");b.send("Hello");

}

outputfrom Hyd:Hellofrom Mum:Hellofrom Kol:Hello

Write a program to create some radio stations.Show a message sent by a station is received by allother stations.

Page 70: object oriented concepts

Digitech Technologies 70

Different ways of class implementation

#include<iostream.h>

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

#include<iostream.h>

class demo { int num; public: demo(); demo(int); void show(); };

demo::demo():num(0){}

demo::demo(int a):num(a){}

void demo::show() { cout<<num<<endl; }

void main(){ demo a,b(45); a.show(); b.show();}

Page 71: object oriented concepts

Digitech Technologies 71

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;

Page 72: object oriented concepts

Digitech Technologies 72

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 memberspublic:short GetDayOfMonth ();char* GetDateOfWeek ();

};

Page 73: object oriented concepts

Digitech Technologies 73

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

The class should be declared within the#ifndef _FILENAME_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

#ifndef _EMPLOYEE_H#define _EMPLOYEE_H// Class definition here#endif // _EMPLOYEE_H

Page 74: object oriented concepts

Digitech Technologies 74

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 Footer Block : All files should have this footer at the end of the file.

/***************************************************** File : <filename>* Description : <description>* Author : <author> <company>* Version : <version number>* Date : <Date>* Modification log :****************************************************/

/***************************************************** End of <filename>****************************************************/

Page 75: object oriented concepts

Digitech Technologies 75

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

Page 76: object oriented concepts

Digitech Technologies 76

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

Page 77: object oriented concepts

Digitech Technologies 77

Coding standards and naming conventions

public://Method to get the Employee numberint GetEmployeeNumber();

//Method to get the Employee namechar* GetEmployeeName();

//method to set the Employee numbervoid SetEmployeeNumber(int iEmpNum);

//Method to set the Employee namevoid SetEmployeeName(char* pcEmpName);

};

#endif // _EMPLOYEE_H

/******************************************************* End of Employee.h*******************************************************/

Page 78: object oriented concepts

Digitech Technologies 78

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

Page 79: object oriented concepts

Digitech Technologies 79

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

Page 80: object oriented concepts

Digitech Technologies 80

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

Page 81: object oriented concepts

Digitech Technologies 81

Method chaining(returning current obj. reference)

#include<iostream.h>class demo{

int num;public:

demo():num(0){}demo(int k):num(k){}void show(){ cout<<num<<endl; }demo setOne(int k) {

num=k;return *this;

}demo setTwo(int k){

num=k;return *this;

}demo& putOne(int k) { num=k;

return *this;}

demo& putTwo(int k){

num=k;return *this;

}};

void main (){

demo d1(45),d2(45);

d1.setOne(20).setTwo(30);d2.putOne(20).putTwo(30);

d1.show();d2.show();

}Output2030

Page 82: object oriented concepts

Digitech Technologies 82

Aggregation

Aggregation refers to a relationship where one class contains objects of another class as it’s members

Aggregation leads to Has-A relationship

Page 83: object oriented concepts

Digitech Technologies 83

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

Page 84: object oriented concepts

Digitech Technologies 84

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.

Page 85: object oriented concepts

Digitech Technologies 85

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.

Page 86: object oriented concepts

Digitech Technologies 86

String class

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

class str{ char *s; public: str() {

s=new char[1];*s=0;

} str(char *a) {

s=new char[ strlen(a)+1 ];strcpy(s,a);

} void display() {

cout<<s<<endl; }

void copy(char *a) { delete s; s=new char[ strlen(a)+1 ]; strcpy(s,a); } void add(char *a) { char *t t=new char[ strlen(s)+strlen(a)+1 ]; strcpy(t,s); strcat(t,a); delete s; s=t; }};void main(){ str a("hello"),b("welcome"); a.copy("abc"); b.add(" xyz"); a.display(); b.display();}

Outputabcwelcome xyz

Page 87: object oriented concepts

Digitech Technologies 87

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.

Page 88: object oriented concepts

Digitech Technologies 88

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

Page 89: object oriented concepts

Digitech Technologies 89

Copy constructor

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

class str{ char *s; public: : void abc( str k ) { strcpy(k.s,”aaa”); }};

void main(){ str a,b(“Hello”); b.display(); a.abc(b); b.display();}

OutputHelloaaa

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

class str{ char *s; public: : void abc( str k ) { strcpy(k.s,”aaa”); } str( str &m ) { s=new char[ strlen(m.s)+1]; strcpy(s,m.s); }};

void main(){ same as before }

OutputHelloHello

Page 90: object oriented concepts

Digitech Technologies 90

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

Page 91: object oriented concepts

Digitech Technologies 91

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

Page 92: object oriented concepts

Digitech Technologies 92

Friend Functions

Global friend function

#include<iostream.h>class demo{

int num;public:demo():num(0){}demo(int a):num(a){}

int sum1(demo x) { return num+x.num; }friend int sum2(demo,demo);

};

int sum2(demo x,demo y) { return x.num+y.num; }

void main(){

demo a(5),b(7);

cout<<a.sum1(b) <<endl;cout<<sum3(a,b) <<endl;

}

/* output1212*/

Page 93: object oriented concepts

Digitech Technologies 93

Friend Class

#include<iostream.h>

class demo{ int num; public: demo():num(0){} demo(int a):num(a){} friend class abc;};

class abc{ public: void show() { demo k(45); cout << k.num << endl; } void display() { demo k(45); cout << k.num << endl; }};

void main(){ abc a; a.show(); a.display();}

/* Output

45

45

*/

Page 94: object oriented concepts

Digitech Technologies 94

Friend Functions

#include<iostream.h>

class abc{ public: void show(); void display();};

class demo{ int num; public: demo():num(0){} demo(int a):num(a){} friend void abc::show();};

void abc::show(){ demo k(45); cout << k.num << endl;}

void abc::display(){ demo k(45); //cout << k.num << endl;}

void main(){ abc a; a.show(); a.display();}

Page 95: object oriented concepts

Digitech Technologies 95

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.

Page 96: object oriented concepts

Digitech Technologies 96

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.

Page 97: object oriented concepts

Digitech Technologies 97

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

{

}

Page 98: object oriented concepts

Digitech Technologies 98

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.

Page 99: object oriented concepts

Digitech Technologies 99

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

};

Page 100: object oriented concepts

Digitech Technologies 100

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

{str a,b(“hello”),c,d,e;

e=a=”abc”;c=b+”xyz”;d=”123”+b;

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

}

Output

abchellohelloxyz123helloabc

Page 101: object oriented concepts

Digitech Technologies 101

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 typeva_list k;

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

To extract elements from ellipsis usedata_type va_arg( va_list , data_type )

Each call to va_arg returns the next element from ellipsis.

Page 102: object oriented concepts

Digitech Technologies 102

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

}

void main(){

abc(3,44,55,66);abc(2,67,44);abc(0);abc(5,23,77,55,48,34);

}

Output44 55 66 67 44

23 77 55 48 34

Page 103: object oriented concepts

Digitech Technologies 103

Operator overloading

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

class array

{int *n,max;public: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];

}

};

void main(){

array a(10,56,7,89,45,33,8,9,32,11,30);

a[3]=600;for(int i=0;i<10;i++) cout << a[i] << “ “;

}

Page 104: object oriented concepts

Digitech Technologies 104

Operator overloading

Simulation of **, the power operator

#include<iostream.h>

class Number{ int num; public: Number():num(0){} Number(int a):num(a){} int operator*(Number &a) { 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;

}};

void main(){ Number a(5),b(3); cout<<a*b<<endl<<a**b<<endl;}

/* Output15125*/

Page 105: object oriented concepts

Digitech Technologies 105

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

void main(){ demo a,b(23),c=b,d=45; a=90; a.display(); b.display(); c.display(); d.display(); a=”Hello”; a.display();}

Output 90 23 23 45 5

Page 106: object oriented concepts

Digitech Technologies 106

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}

Page 107: object oriented concepts

Digitech Technologies 107

Operator overloading

Example for User-defined to User-defined conversion#include<iostream.h>class celsius;class fahrenheit{

float f;public:fahrenheit():f(0){}fahrenheit(float a):f(a){}void display(){ cout<<f<<endl; }operator celsius();

};

class celsius{ float c;

public:celsius():c(0){}celsius(float a):c(a){}void display(){ cout<<c<<endl; }operator fahrenheit() { return c*9.0/5.0 + 32.0; }

};

fahrenheit::operator celsius(){

return (f-32.0)*5.0/9.0;}

void main(){

celsius a,b(30);fahrenheit c,d(100);

a=(celsius)d;c=(fahrenheit)b;

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

}

Page 108: object oriented concepts

Digitech Technologies 108

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’.

Page 109: object oriented concepts

Digitech Technologies 109

Inheritance

Page 110: object oriented concepts

Digitech Technologies 110

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

Page 111: object oriented concepts

Digitech Technologies 111

Inheritance

Inheritance Relationship

• “is a” relation exists between the derived class and base class.

• Trainee is an EmployeeEmployee

Trainee

Page 112: object oriented concepts

Digitech Technologies 112

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.

Page 113: object oriented concepts

Digitech Technologies 113

Inheritance

Types of Inheritance based on structure

Page 114: object oriented concepts

Digitech Technologies 114

Inheritance

Derivation type

Base class member

Access in derived class

Private private (inaccessible)

  public private

  protected private

     

Public private (inaccessible)

  public public

  protected protected

     

Protected private (inaccessible)

  public protected

  protected protected

Derivation types

Derivation type determines the base members accesibility in the derived class

Page 115: object oriented concepts

Digitech Technologies 115

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.

Page 116: object oriented concepts

Digitech Technologies 116

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

Page 117: object oriented concepts

Digitech Technologies 117

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.

Page 118: object oriented concepts

Digitech Technologies 118

Inheritance

#include<iostream.h>

class base{

int num;public:

base():num(0){}base(int k):num(k){}void show()

{ cout<<num<<endl; }};

class derive : public base{

int num;public:

derive():num(0){}derive(int k):base(k/2),num(k){}void display()

{ cout<<num<<endl; }};

void main(){ derive d(45);

d.show(); d.display();}

/* output2245*/

Page 119: object oriented concepts

Digitech Technologies 119

Inheritance

Method 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.

Page 120: object oriented concepts

Digitech Technologies 120

Inheritance

#include<iostream.h>

class base{

int num;public:

base():num(0){}base(int k):num(k){}void show()

{ cout<<num<<endl; }};

class derive : public base{

int num;public:

derive():num(0){}derive(int k):base(k/2),num(k){}void show()

{ cout<<num<<endl; }};

void main(){ derive d(45);

d.base::show(); d.show();}

/* output2245*/

Page 121: object oriented concepts

Digitech Technologies 121

Inheritance

#include<iostream.h>

class twoD{ int x,y; public: twoD():x(0),y(0){} twoD(int a,int b):x(a),y(b){} void display() {

cout << x << " " << y << " "; } void setx(int a){ x=a; } void sety(int a){ y=a; }};

class threeD{ twoD td; int z; public: threeD():z(0){} threeD(int a,int b,int c):z(c) { td.setx(a); td.sety(b); } void display() { td.display();

cout << z << " "; } void setx(int a){ td.setx(a); } void sety(int a){ td.sety(a); } void setz(int a){ z=a; }};

void main(){ threeD td(56,34,90); td.display(); cout<<endl; td.setx(51); td.display();}

Point2D and Point3D ( without inheritance )

Page 122: object oriented concepts

Digitech Technologies 122

Inheritance

#include<iostream.h>

class twoD{ int x,y; public: twoD():x(0),y(0){} twoD(int a,int b):x(a),y(b){} void display() {

cout << x << " " << y << " "; } void setx(int a){ x=a; } void sety(int a){ y=a; }};

class threeD : public twoD{ int z; public: threeD():z(0) { } threeD(int a,int b,int c): twoD(a,b),z(c){}

void display() {

twoD::display(); cout << z << " ";

} void setz(int a){ z=a; } };

void main(){ threeD td(56,34,90); td.display(); cout<<endl; td.setx(51); td.display();}

Point2D and Point3D ( with inheritance )

Page 123: object oriented concepts

Digitech Technologies 123

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

::

Page 124: object oriented concepts

Digitech Technologies 124

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. 

Page 125: object oriented concepts

Digitech Technologies 125

Inheritance

#include<iostream.h> class base{ public: base() { cout<<"from base default\n"; } base(base &a) { cout<<"from base copy const\n"; } ~base() { cout<<”from base destructor\n”; }};class derive : public base{ 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;}

Output:from base defaultfrom derive defaultfrom base copy constfrom derive copy constfrom derive destructorfrom base destructorfrom derive destructorfrom base destructor

Page 126: object oriented concepts

Digitech Technologies 126

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.

Page 127: object oriented concepts

Digitech Technologies 127

Inheritance

#include<iostream.h>

class common_base{ 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; }};

virtual inheritance

Page 128: object oriented concepts

Digitech Technologies 128

Inheritance

class base2 : virtual public common_base{ int x; 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){} derive(int a):common_base(a), base1(a),base2(a),x(a){} void show() { cout<<x<<endl; }};

void main(){ derive d(25); d.show(); d.common_base::show(); d.base1::show(); d.base2::show();}

virtual inheritance

Page 129: object oriented concepts

Digitech Technologies 129

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

Page 130: object oriented concepts

Digitech Technologies 130

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

Page 131: object oriented concepts

Digitech Technologies 131

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

};

Page 132: object oriented concepts

Digitech Technologies 132

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

Page 133: object oriented concepts

Digitech Technologies 133

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

Page 134: object oriented concepts

Digitech Technologies 134

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

Page 135: object oriented concepts

Digitech Technologies 135

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

} } }

Page 136: object oriented concepts

Digitech Technologies 136

Inheritance - Example

int i;

long msum=0;for(i=0;i<mmax;i++){ m[i].display(); cout<<m[i].pay()<<endl; msum=msum+m[i].pay();}

long ssum=0;for(i=0;i<smax;i++){ s[i].display(); cout<<s[i].pay()<<endl; ssum=ssum+s[i].pay();}

long wsum=0; for(i=0;i<wmax;i++) {

w[i].display();cout<<w[i].pay()<<endl;wsum=wsum+w[i].pay();

}

cout<<msum+ssum+wsum <<endl; }/* end of main */

The for loops are identicalexcept the object referencesThis is because the data is stored in three different arrays

Page 137: object oriented concepts

Digitech Technologies 137

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

Page 138: object oriented concepts

Digitech Technologies 138

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

}

Page 139: object oriented concepts

Digitech Technologies 139

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

} }}

Page 140: object oriented concepts

Digitech Technologies 140

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

Page 141: object oriented concepts

Digitech Technologies 141

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.

Page 142: object oriented concepts

Digitech Technologies 142

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.

Page 143: object oriented concepts

Digitech Technologies 143

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;

} outputRavi Kumar BRavi Kumar B 5 90 500 102

Page 144: object oriented concepts

Digitech Technologies 144

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;

} outputRavi Kumar B 5 90 500 102Ravi Kumar B 5 90 500 102

Page 145: object oriented concepts

Digitech Technologies 145

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

Page 146: object oriented concepts

Digitech Technologies 146

Polymorphism Polymorphism

class employee { : public: employee(){} employee(…){…} virtual void display(){ … } };::void main(){

employee *e=new sales_person("Ravi Kumar",5,90,500,102);

e->display();cout<<e->pay()<<endl;

}

Compiler Error:'pay' : is not a member of 'employee'

Page 147: object oriented concepts

Digitech Technologies 147

Polymorphism Polymorphism

class employee { : public: employee(){} employee(…){…} virtual void display(){ … } virtual int pay(){ return 0; }};::void main(){

employee *e=new sales_person("Ravi Kumar",5,90,500,102);

e->display();cout<<e->pay()<<endl;

}

OutputRavi Kumar B 5 90 500 102 950

Page 148: object oriented concepts

Digitech Technologies 148

Polymorphism Polymorphism

class employee { : virtual void display(){ … } virtual int pay(){ return 0; }};class manager : public employee{ : public: // int pay(){ return sal; }};:void main(){

employee *e=new manager("Ravi Kumar",19000);e->display();cout<<e->pay()<<endl;

}

OutputRavi Kumar A 19000 0

manager pay

Page 149: object oriented concepts

Digitech Technologies 149

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.

Page 150: object oriented concepts

Digitech Technologies 150

Polymorphism Polymorphism Polymorphism

class employee { : virtual void display(){ … } virtual int pay()=0;};class manager : public employee{ : public: // int pay(){ return sal; }};:void main(){

employee *e=new manager("Ravi Kumar",19000);e->display();cout<<e->pay()<<endl;

}

Compiler Error:'manager' : cannot instantiate abstract class

Page 151: object oriented concepts

Digitech Technologies 151

Polymorphism Polymorphism Polymorphism Polymorphism

class employee { : virtual void display(){ … } virtual int pay()=0;};class manager : public employee{ : public: int pay(){ return sal; }};:void main(){

employee *e=new manager("Ravi Kumar",19000);e->display();cout<<e->pay()<<endl;

}

Output:Ravi Kumar A 19000 19000

Page 152: object oriented concepts

Digitech Technologies 152

Polymorphism

#include<iostream.h>class shape{ 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; }

};

Shape Example

Page 153: object oriented concepts

Digitech Technologies 153

Polymorphism

class rectangle : public shape{

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;

}

Shape Example

Page 154: object oriented concepts

Digitech Technologies 154

Polymorphism

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

class sortable{public: virtual int compare(sortable*)=0;};

class sort{public: static void bubble(sortable **e,int max) {

sortable *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;

} }};

Any user-defined types canbe sorted using the sort class, provided the class defines ‘compare’ method.

General purpose sort Example

Page 155: object oriented concepts

Digitech Technologies 155

Polymorphism

class employee : public sortable{

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;

}};

General purpose sort Example

Page 156: object oriented concepts

Digitech Technologies 156

Polymorphism

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

sort::bubble((sortable**)e,MAX);

for(int i=0;i<MAX;i++)e[i]->show();

}

OutputSham --- 8000Ravi --- 9000Sing --- 10000Neha --- 11000Giri --- 12000

General purpose sort Example

Page 157: object oriented concepts

Digitech Technologies 157

Polymorphism

#include<iostream.h>

class base{public:

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

~derive(){ cout<<"from derive destructor\n"; }};

void main(){ base *d=new derive(); delete d;}

Virtual Destructor

Outputfrom base destructor

Page 158: object oriented concepts

Digitech Technologies 158

Polymorphism

#include<iostream.h>

class base{public:

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

~derive(){ cout<<"from derive destructor\n"; }};

void main(){ base *d=new derive(); delete d;}

Outputfrom derive destructorfrom base destructor

Virtual Destructor

Page 159: object oriented concepts

Digitech Technologies 159

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.

Page 160: object oriented concepts

Digitech Technologies 160

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.

Page 161: object oriented concepts

Digitech Technologies 161

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.

Page 162: object oriented concepts

Digitech Technologies 162

Exception Handling

:try{

:if( … ) throw exception;:

}catch (type argument){

:}:

Syntax for try and catch blocks

Page 163: object oriented concepts

Digitech Technologies 163

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.

Page 164: object oriented concepts

Digitech Technologies 164

Exception Handling

#include<iostream.h>

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

}

Simple example

Page 165: object oriented concepts

Digitech Technologies 165

Exception Handling

#include<iostream.h>

int abc(int x,int y){ 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 {

Raising exception from within try block and from outside try block

Page 166: object oriented concepts

Digitech Technologies 166

Exception Handling

c=abc(a,b);cout<<c<<endl;

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

Raising exception from within try block and from outside try block

Page 167: object oriented concepts

Digitech Technologies 167

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{

:}

Page 168: object oriented concepts

Digitech Technologies 168

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.

Page 169: object oriented concepts

Digitech Technologies 169

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

}

Page 170: object oriented concepts

Digitech Technologies 170

Templates

#include<iostream.h>#include<string.h>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;}

void main(){ int a=10,b=20; 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;}

Output20x88.34welcome

Function Template Example

Page 171: object oriented concepts

Digitech Technologies 171

Templates

#include<iostream.h>template<class T>class demo{ T data; public:

demo(){}

demo(T a):data(a){}void display(){ cout << data << endl;

}};

void main(){ demo<int> a(67); demo<char*> b(“hello”); demo<float> c;

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

Output

67hello-1.07374e+008

Class Template Example

Page 172: object oriented concepts

Digitech Technologies 172

Templates

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

}}

General Purpose Sorting Template Function

Page 173: object oriented concepts

Digitech Technologies 173

Templates

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

};

General Purpose Sorting Template Function

Page 174: object oriented concepts

Digitech Technologies 174

Templates

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

for(int i=0;i<MAX;i++)e[i]->show();

}

General Purpose Sorting Template Function

OutputSham --- 8000Ravi --- 9000Sing --- 10000Neha --- 11000Giri --- 12000

Page 175: object oriented concepts

Digitech Technologies 175

Templates

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

Class Template : Array Example

Page 176: object oriented concepts

Digitech Technologies 176

Templates

T& operator[](int a) {

a=a-s; if(a<0 || a>=max ) { cout<<"error in index"<<endl; exit(1); } return n[a]; }};

void main(){ 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] << " ";}

Class Template : Array Example

Output

56 7 89 45 33 8 9 32 11 30Hello Welcome

Page 177: object oriented concepts

Digitech Technologies 177

Templates

#include<iostream.h>

template<class T>class demo{

T data;public:demo(){}demo(T k):data(k){}void show();

};

template<class T>void demo<T>::show(){

cout<<data<<endl;}

template<class T>class derive : public demo<T>{};

Output45Hello-1.07374e+008

void main(){

demo<int> a(45);demo<char*> b("Hello");demo<float> c;

a.show();b.show();c.show();

}

Page 178: object oriented concepts

Digitech Technologies 178

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

Page 179: object oriented concepts

Digitech Technologies 179

IO Streams

Source ProgramReads

Program Destination

Writes

Stream

Stream

Page 180: object oriented concepts

Digitech Technologies 180

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

fstream ofstreamifstream

Page 181: object oriented concepts

Digitech Technologies 181

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

Page 182: object oriented concepts

Digitech Technologies 182

IO Streams

Methods for setting/resetting formatting flags setf(long flag) sets specified flag without affected other flagsunsetf(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<<" ";cout.unsetf(ios::hex);cout.setf(ios::dec);cout<<70<<endl;

}

Output41 7041 70

Page 183: object oriented concepts

Digitech Technologies 183

IO Streams

Method for setting field widthwidth(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<<'*';cout.width(10);cout.setf(ios::right);cout.unsetf(ios::left);cout<<70<<'*'<<endl;

}

Output*65 ** 70**65 ** 70*

Page 184: object oriented concepts

Digitech Technologies 184

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);cout.unsetf(ios::left);cout.fill('-');cout<<70<<endl;

}

Output65**--------70

Page 185: object oriented concepts

Digitech Technologies 185

IO Streams

Unformatted input methodschar 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.

Page 186: object oriented concepts

Digitech Technologies 186

IO Streams

#include<iostream.h>

void main(){

char s[80];

cout<<"Enter name : ";cin>>s;

cout<<s<<endl;}

OutputEnter name : Ravi KumarRavi

#include<iostream.h>

void main(){

char s[80];

cout<<"Enter name : ";cin.get(s,80);

cout<<s<<endl;}

OutputEnter name : Ravi KumarRavi Kumar

Page 187: object oriented concepts

Digitech Technologies 187

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 : ";cin.get(s2,80);

cout<<s1<<endl<<s2<<endl;}

OutputEnter name : raviEnter name : giriravigiri

Page 188: object oriented concepts

Digitech Technologies 188

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

Page 189: object oriented concepts

Digitech Technologies 189

IO Streams

Formatted input methodsThe 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 methodsThe 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);

:

Page 190: object oriented concepts

Digitech Technologies 190

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;

}

Page 191: object oriented concepts

Digitech Technologies 191

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;cout<<e;

}

Output

Enter name : Ravi KumarEnter sal : 9000Ravi Kumar --- 9000

Page 192: object oriented concepts

Digitech Technologies 192

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;

}

Page 193: object oriented concepts

Digitech Technologies 193

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 recordcan be found. ( rec_number - 1 ) * ( size of record )

Page 194: object oriented concepts

Digitech Technologies 194

IO Streams

File stream classes are defined in fstream.h header file.Ifstreamifstream()

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 )

ofstreamofstream()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) ...

Page 195: object oriented concepts

Digitech Technologies 195

IO Streams

File Open Modesios::in file opened to inputios::out file opened to outputios::app file opened to append records

File Seek Directionios::beg set file pointer from beginning of the fileios::cur set file pointer from current position of the fileios::end set file pointer from end of the file

File Status Methodsint good() returns true value if the last operations successfulint bad() returns true value if last operation failedint eof() returns true value if end of file is reached

Page 196: object oriented concepts

Digitech Technologies 196

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;

}

Page 197: object oriented concepts

Digitech Technologies 197

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

}

Page 198: object oriented concepts

Digitech Technologies 198

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

}

Page 199: object oriented concepts

Digitech Technologies 199

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

Page 200: object oriented concepts

Digitech Technologies 200

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

}

Page 201: object oriented concepts

Digitech Technologies 201

IO Streams

ManipulatorsManipulators 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 typesBuilt-in manipulators without arguments dec - sets output format to decimal

oct - sets output format to octalhex - sets output format to hexadecimalendl - generates newline sequence

#include<iostream.h>void main()

{ cout << hex << 65 << endl << dec << 70 << endl;}

Output4170

Page 202: object oriented concepts

Digitech Technologies 202

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.

Page 203: object oriented concepts

Digitech Technologies 203

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

Output65********------------------65

Page 204: object oriented concepts

Digitech Technologies 204

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

Page 205: object oriented concepts

Digitech Technologies 205

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 << set(20,1,'-') << 65 << endl; }

Output65********------------------65

Page 206: object oriented concepts

Digitech Technologies 206

Smart Pointers

•Take care of automatic initialization and cleanup

•Take care of dangling pointers

•Keep track of dynamically allocated objects shared by multiple owners

Page 207: object oriented concepts

Digitech Technologies 207

Smart Pointers

void abc(){ demo *p(new demo); p->doSomething(); delete p;}

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

void abc(){ demo *p; try { p=new demo; p->doSomething(); delete p; } catch(…){…}

void abc(){ auto_ptr<demo> p(new demo); try {

p->doSomething(); } catch(…){…}

Page 208: object oriented concepts

Digitech Technologies 208

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;

}};

Page 209: object oriented concepts

Digitech Technologies 209

Smart Pointers( Simple Example )

class RCPtr{ demo *pointee;public: RCPtr(demo *t):pointee(t) { pointee->addReference(); } RCPtr(const RCPtr &t):pointee(t.pointee) {

pointee->addReference(); } ~RCPtr() {

if( pointee->removeReference()==0 ) delete pointee; } demo* operator->(){ return pointee; } demo& operator*(){ return *pointee; }};

void main(){

RCPtr t(new demo(56));t->show();(*t).show();

}

Output56-156-1

Page 210: object oriented concepts

Digitech Technologies 210

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 Operatortypeid( type-id )ortypeid( 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.

Page 211: object oriented concepts

Digitech Technologies 211

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

Page 212: object oriented concepts

Digitech Technologies 212

RTTI - Run-Time Type Identification

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

class employee{public:

virtual void show() { cout<<"from employee\n"; }};

class manager : public employee{public:

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

For RTTI make settings as shown:Project > Settings > C/C++ tab > Category - C++ Language > Check Run-Time Type information

Page 213: object oriented concepts

Digitech Technologies 213

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

Page 214: object oriented concepts

Digitech Technologies 214

Standard Template Library ( STL )

The STL is a generic library that provides solutions to managingof 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

Page 215: object oriented concepts

Digitech Technologies 215

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

Page 216: object oriented concepts

Digitech Technologies 216

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

Page 217: object oriented concepts

Digitech Technologies 217

Standard Template Library ( STL )

STL Containers

vector

deque

list

set/multiset

Map/multimap

Page 218: object oriented concepts

Digitech Technologies 218

Standard Template Library ( STL )

#include<iostream>#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;

vector example

Page 219: object oriented concepts

Digitech Technologies 219

Standard Template Library ( STL )

cout<<endl;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;v.erase( it );

cout<<endl;for(i=0;i<v.size();i++)

cout << v.at(i) << " ";

cout<<endl;}

Output45 59 22 78 1445 59 88 78 1445 59 88 78 1445 59 78 14

vector example

Page 220: object oriented concepts

Digitech Technologies 220

Standard Template Library ( STL )

#include<iostream>#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++)cout << d[i] << " ";

cout<<endl;}

Output14 78 45 59 22

deque example

Page 221: object oriented concepts

Digitech Technologies 221

Standard Template Library ( STL )

#include<iostream>#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++;

}

list example

Page 222: object oriented concepts

Digitech Technologies 222

Standard Template Library ( STL )

cout<<endl;while( !l.empty() ){

cout << l.front() << " ";l.pop_front();

}

cout<<endl;}

/*Output78 45 59 22 1478 45 59 22 14*/

list example

Page 223: object oriented concepts

Digitech Technologies 223

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

Page 224: object oriented concepts

Digitech Technologies 224

Standard Template Library ( STL )

#include<iostream>#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++;}

cout<<endl; }

Output14 22 45 59 78

set example

Page 225: object oriented concepts

Digitech Technologies 225

Standard Template Library ( STL )

#include<iostream>#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;

}};

set example

Page 226: object oriented concepts

Digitech Technologies 226

Standard Template Library ( STL )

void main(){ 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++){

it->show();it++;

}}

OutputGanesh 2200Giri 8900Kiran 7700Ravi 6700Sham 4500

set example

Page 227: object oriented concepts

Digitech Technologies 227

Standard Template Library ( STL )

#include<iostream>#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) );m.insert( pair<int,int>(0,30) );m.insert( pair<int,int>(3,40) );m.insert( pair<int,int>(4,50) );

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

}

Output

30 10 20 40 50

map example

Page 228: object oriented concepts

Digitech Technologies 228

Standard Template Library ( STL )

#include<iostream>#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;}/*Output12 34 36 44 44 56 78 78 90 95*/

sort example

Page 229: object oriented concepts

Digitech Technologies 229

Standard Template Library ( STL )

#include<iostream>#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;}/*OutputPosition:4 Value:34*/

find example

Page 230: object oriented concepts

Digitech Technologies 230

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 apointer to a function, but there are some important differences

- pass function objects to algorithms at compile time

- increases efficiency, by inlining the corresponding call

Page 231: object oriented concepts

Digitech Technologies 231

Standard Template Library ( STL )

#include<iostream>#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;

Function Object Example

Page 232: object oriented concepts

Digitech Technologies 232

Standard Template Library ( STL )

sort(n,n+10);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;

}Output12 34 36 44 44 56 78 78 90 9595 90 78 78 56 44 44 36 34 1295 90 78 78 56 44 44 36 34 12

Function Object Example


Recommended