Sie sind auf Seite 1von 232

Object Oriented Concepts

Course Objective To introduce the principles and concepts behind Object Oriented Programming To explain how complex scenarios can be handled easily using Object Oriented Technology

To learn good OO design practices

Digitech Technologies

Object Oriented Concepts


Limitations of Structured Programming Modules are tightly coupled Scope of reusability is limited As the code size grows, maintaining code becomes difficult Any major changes required to functionality later may result in a lot of changes in code

Digitech Technologies

Object Oriented Concepts


What is an Object ? An object Is an unique, identifiable, self-contained entity that contains attributes and behaviors. Is modeled after real world objects Can be viewed as a "black box" which receives and sends messages Examples Car ,Telephone , Pen etc

Digitech Technologies

Object Oriented Concepts


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

Digitech Technologies

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 doesnt have to understand how the engine works to drive a car

Engine

Digitech Technologies

Driving

Object Oriented Concepts


Abstraction Example (Making of a Computer chip)
Binary Counter
U/D B1

Capacitor Resistor

Buffer
Reset B8

Inverter

Carry out ENB

Diode

AND Gate

Register
A Q1

XOR Gate Transistor OR Gate MOSFET Basic Electronic Components


H Q8

ENB

Boolean Logic Gates Digital circuits built Central Processing unit built using basic using Boolean logic Built using complex electronic components gates digital circuits st Level abstraction) nd Level abstraction) rd level abstraction) (1 (2 (3 Digitech Technologies 6

Object Oriented Concepts

Encapsulation Encapsulate = En + Capsulate En = In a Encapsulate = In a Capsule Encapsulation means localization of information of knowledge within an object. Encapsulation also means Information hiding Example: A cars dashboard hides the complexity and internal workings of its engine.

Digitech Technologies

Object Oriented Concepts


Encapsulation (Data hiding) Process of hiding the members from outside the class Implemented using the concept of access specifiers public, private etc. Typically in a class State is private (not accessible externally) Behavior is public (accessible externally)

Digitech Technologies

Object Oriented Concepts


Relationships Different types of relationships can exist between classes There are 3 types of relationships Is-A (or Kind-Of) Has-A (or Part-Of) Uses-A

Digitech Technologies

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
Loan -LoanAmount : double -InterestRate : float -Duration : int -CustomerID : int +GetInterestRate() : float +GetLoanAmount() : double +GetDuration() : int +GetCustomerID() : int +SetDuration() +SetLoanAmount() +SetInterestRate() +SetCustomerID()

parent or Super class)


The class which inherits from another

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

class is called as derived class

Inherits

Wealth

Digitech Technologies

10

Object Oriented Concepts


Multi-Level Inheritance A class can inherit from another class Derived class inherits all the members of base class Another class can inherit from the derived class The new class inherits all the member of all its ancestor classes
Loan -LoanAmount : double -InterestRate : float -Duration : int -CustomerID : int +GetInterestRate() : float +GetLoanAmount() : double +GetDuration() : int +GetCustomerID() : int +SetDuration() +SetLoanAmount() +SetInterestRate() +SetCustomerID()

Data required for all types loans

BusinessLoan
-InterestType : char -Term : char +GetInterestType() : char +SetInterestType() +GetTerm() : char +SetTerm()
Data additionally required for BusinessLoan. Common members inherited from base class

LargeBusinessLoan
-MoratoriumPeriod : int +GetMoratoriumPeriod() : int +SetMoratoriumPeriod()

Special type of BusinessLoan. Has some more additional members

Digitech Technologies

11

Object Oriented Concepts


Multiple Inheritance Concept of a class inheriting from more than one base class Example: A Hybrid car can inherit from FuelCar and BatteryCar
FuelCar
-TankCapacity : float -TypeOfFuel : char

ElectricCar
-BatteryCapacity : float

HybridCar

Digitech Technologies

12

Object Oriented Concepts


Advantages and Disadvantages of inheritance Advantages Promotes reusability Helps in better abstraction, thereby resulting in better design Eliminates duplication of code Disadvantages Overuse of this concept (in cases where not necessary) leads to bad design Wrong usage of inheritance can lead to code and design complexity
Digitech Technologies 13

Object Oriented Concepts


Has-A Relationship - Aggregation class HousingLoan has PropertyDetails as a member variable class PropertyDetails has Address as a member variable Address is a generic class which can store any address (address of a property or address of a person etc)
HousingLoan
-CustomerID : int -Duration : int -InterestRate : float -LoanAmount : double -TypeOfInterest : char -PropertyDetails : PropertyDetails +GetInterestRate() : float +SetInterestRate() +GetLoanAmount() : double +SetLoanAmount() +GetCustomerID() : int +SetCustomerID() +GetDuration() : int +SetDuration() +GetTypeOfInterest() : char +SetTypeOfInterest()

Address PropertyDetails
Has A

Part of

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

Has A

Part of

Digitech Technologies

-AddressLine1 : char -AddressLine2 : string -City : string -Zip : string -State : string +GetAddressLine1() : string +SetAddressLine1() +GetAddressLine2() : string +SetAddressLine2() +GetCity() : string +SetCity() +GetZip() : string +SetZip() +GetState() : string +SetState()

14

Object Oriented Concepts


Message Passing An object by itself may not be very useful Useful work happens when one object invokes methods on other objects Example: A car by itself is not capable of any activity A person interacts with the car using steering wheel, gauges on dashboard and various pedals This interaction between objects result in change of state achieving something useful
Digitech Technologies 15

Object Oriented Concepts


Polymorphism Refers to an objects ability to behave differently depending on its type Poly = many morph = form This characteristic enables making extensions to a classs functionality Two features of an object which achieve polymorphism Method Overloading (or Function overloading) Method Overriding (or Function overriding)
Digitech Technologies 16

Object Oriented Concepts


What is a Class ? A Class Is a blue print used to create objects. Is a software template that defines the methods and variables to be included in a particular kind of Object. Examples : Animal, Human being, Automobiles, Bank Account, Customer

Digitech Technologies

17

Object Oriented Concepts


Class Contains State (Member variables) Variables defined inside a class form the State of the class

Not exposed to external world


Behavior (Member Methods) Behavior exhibited by the class to external world Functions defined inside the class form the behavior of class Exposed to external world
ge an Ch ea G r
A e cc r le e at
Number of Gears 5 Seating Capacity 7 Number of Doors 4 Current Speed 45 km/h State is internal to the object. Not exposed to external world/other objects Current Gear 3

(BEHAVIOR)

Interface to external world (Through Methods/ Functions only)

(STATE)
ak Do e (S w lo n) w

Digitech Technologies

Br

18

Object Oriented Concepts


Example: Objects and Classes

object

class
Class Student Name

Regn_No
setName()
Jodie R001
Daria R002

Jane R003

Brittany R004

setRegnNo() CalcMarks()
19

Digitech Technologies

Object Oriented Concepts


Method Overloading Practice of using same method name to denote several different operations Some OO languages allow overloading of both functions and Operators (like +, - etc) Example: Consider a String class which is a utility class designed to abstract and simplify string operations

Append functions are overloaded to accept different types of data

Digitech Technologies

20

Object Oriented Concepts


Method Overriding Refers to the practice of providing a different implementation of a method in the derived class Method in derived class may be completely different from the implementation in the base class Example 1: A base class Shape has function Draw which draws the shape on screen The derived classes Line, Rectangle, Circle etc. implement their own Draw methods which draw respective shapes on screen
Digitech Technologies 21

Object Oriented Concepts


Method Overriding - Examples

Shape +Draw()

Abstract class (Does not implement Draw function)

Loan
-LoanAmount : double -InterestRate : float -Duration : int -CustomerID : int +GetInterestRate() : float +GetLoanAmount() : double +GetDuration() : int +GetCustomerID() : int +SetDuration() +SetLoanAmount() +SetInterestRate() +SetCustomerID() +Report()

Line
-... +Draw()

Rectangle
-... +Draw()

Circle
-... +Draw()

Octagon
-... +Draw()

Simple Loan Report

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

Housing Loan Report

Digitech Technologies

22

Structured Programming (Procedure-Oriented)


The structured programming paradigm is: Decide which procedure you want Use the best algorithm you can find Here the focus is on the algorithm required to perform the desired computation Complexity hiding is also one of the objectives in structured programming In this style of programming, importance is given to procedure (logic) and not to the data on which these procedures operateCourse Objective
Digitech Technologies 23

Limitations of Structured Programming


Modules are tightly coupled Scope of reusability is limited As the code size grows, maintaining code becomes difficult Any major changes required to functionality later may result in a lot of changes in code

Digitech Technologies

24

Procedural versus Object Oriented Programming


In procedural programming, functions operate based on either local or global data In Object oriented programming, Objects interact with other objects by passing message

Digitech Technologies

25

Object Oriented Concepts


Abstraction: Process of forming of general and relevant concept from more complex scenarios. Encapsulation: Localization of information within an object. This also leads to Information Hiding Inheritance: Is a process by which one object acquires the properties of another object Polymorphism: Is a characteristic of OO Programming which allows one interface to control access to a general class of actions. The specific action is determined by the exact nature of the situation.

Digitech Technologies

26

Basics of C++
C++ is an Object Oriented programming language It can be considered as a super set of C This enables backward compatibility Bjarne Stroustrup first invented C with Classes and then it was renamed to C++ in 1983. In 1997, ANSI/ISO standards committee standardized C++ Like C, C++ is also case sensitive.

C++ C

Digitech Technologies

27

cin and cout Basics


cin and cout are objects of C++, used with standard input and standard output device. cin and cout objects use >> and << operators. The << is referred to as the insertion operator and >> operator is called extraction operator. cin and cout objects with >> and << are similar to scanf and printf
#include<iostream.h> #include<stdio.h> int main() { printf("%d %c\n",65,65); cout<<65<<" "<<(char)65<<endl; return 0; }
Digitech Technologies

Output 65 A 65 A
28

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; else cout << "Invalid input\n"; } cin.clear(); output Enter two numbers 45 Hello Invalid input Enter two numbers 45 55 100

Digitech Technologies

29

Data types of C++

Digitech Technologies

30

C++ comments
C++ is backward compatible with C C Style comments are also supported C Style comments are used to write function headers , file headers etc Example: /**************************************************** * This style of commenting is used for functions and files *****************************************************/ C++ style of comments are single line comments Any text after // is comment till the end of the line Example: // This is for single line comment fArea = fRadius * fRadius * PI ; // calculating area of Circle
Digitech Technologies 31

Control Structures

Control Structures are statements which changes the execution sequence of the program C++ supports all the control structures supported in C If, else if, else

switch case
for loop while loop do while

Digitech Technologies

32

C and C++ differences


In C the main function can be made recursive, but not in C++. In C++ the variables can be declared any where. The advantage is a variable can be declared near its use. In C new structure variables are created using struct struct_name var_list; In C++ the struct keyword is not required. struct_tag itself serves as type name. struct_name var_list; Scope resolution operator (::) a) Unary form: ::object refers to an object of global scope. b) Binary form: class_name::member defines a member that belongs class_name
Digitech Technologies 33

C and C++ differences


#include<iostream.h> #include<stdio.h> int a=100; void main() { int a=45; int printf=78; int cout=55; ::printf("%d %d %d\n",printf , a , ::a ); } output 78 45 100 55

::cout<<cout<<endl;

Digitech Technologies

34

C and C++ differences


In C++ a constant variable must be initialized but not in C. All standard library functions must have prototypes in C++. C++ supports C type-cast syntax and also got a new syntax syntax : (data_type)expr C++ syntax : data_type(expr)
#include<stdio.h> void main() { int a=300; char b; b=a; printf(%d\n,b); printf(%d\n,(char)a); printf(%d\n,char(a)); }

Output 44 44 44

Digitech Technologies

35

C and C++ differences


C++ constants are of two types Logical constant Logical constants are internally handled as macros. A Logical constant does not exist in memory. A const declaration is taken as logical constant if the initial value is known.

Physical constant

Physical constants are provided sufficient memory space. A const declaration is taken as physical constant if the initial value is given at run-time.
Digitech Technologies 36

C and C++ differences


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.
Digitech Technologies 37

C and C++ differences


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

void abc(int a,int b) { cout << a << " " << b <<endl; }
Digitech Technologies

Output 100 200 10 200 10 20

38

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

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


Digitech Technologies

Output 90 67.55 p

39

C and C++ differences


Reference variables A Reference variable is another name given to an existing variable. Reference variables use the memory given to the existing variable. syntax: data_type &ref_var=var;

#include<iostream.h> void main() { int a=200; int &b=a; cout << &a << " a=10; b=20; cout << a << " " << &b <<endl; " << b << endl;
Digitech Technologies 40

output 0x0012FF7C 20 20

0x0012FF7C

C and C++ differences


#include<iostream.h> void swap(int *a,int *b) { int t=*a; *a=*b; *b=t; } #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 << " << endl; } Output 20 10

" << y

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

" << y

Digitech Technologies

41

C and C++ differences


Returning reference to a variable #include<iostream.h> int& abc(int &a) { return a; } int main() { int x=90; cout << x << endl; abc(x)=300; cout << x << endl; return 0; }
Digitech Technologies

Output 90 300

42

Objects
The real or virtual world is made of objects. The objects exist in some relationship with other objects. A programming language should enable programmers to create objects that behave like real world objects. Software Objects define an abstract representation of real or virtual world entities in order to simulate them. Objects encapsulate a portion of knowledge in a problem domain or the world in which they evolve.

Digitech Technologies

43

Objects

Definitions An atomic entity composed of state, behavior. An Object is a region of storage with associated semantics. An Object is an instance of a data type. An object is a self-contained entity that can maintain its state.

Digitech Technologies

44

Objects
State The state groups the values of all the attributes of an object at a given time, where an attribute is a piece of information. Behavior

The behavior groups all the abilities of an object and describes the actions and reactions of that object. Each individual behavioral component is called an operation. The operations of an object are triggered as a result of an external event, represented in the form of a message sent by another object.

Digitech Technologies

45

C++ struct and class


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.

Digitech Technologies

46

Abstraction
A class or a structure should hide (protect) its data members and expose its operations to outside world. C++ members can be protected or exposed to others by using access specifier. C++ access specifiers

private: A private member can be accessed only from within the class members. public: A public member can be accessed from any where. protected: A protected member is same as private member to the class but it can be accessed in derived type.
Digitech Technologies 47

Access specifiers in a class


Access specifiers specify the scope of the access permitted on a member variable or a member function public: Can be accessed within the class or from outside of the class private: Can be accessed only within the class protected: Same like private but accessible in derived class Data members in a class should always be private Methods that define the behavior of the object and are accessed by other classes are made public Methods which are invoked only within the class and not required to be invoked externally are usually made private They are called helper methods
Digitech Technologies 48

class and struct keywords


class is same as struct except the default access specifier. In struct the default access specifier is public. In class the default access specifier is private struct student { char name[20]; int age; : }s; void main() { s.age=20; class student { char name[20]; int age; : }s; void main() { s.age=20;
Digitech Technologies

// legal

// illegal
49

Objects
An instance of a class in memory In a program, there can be many instances of a class (Many objects of same class) If class can be viewed as a type, then object is a variable of that type

Examples: Trainee is a class. Arun is an Object of Trainee class Educator is a class. Rajagopal is an Object of Educator class

Digitech Technologies

50

Constructor (object initialization)


Using class we can create a complex object that have some hidden data and a set of well defined member funcions. If the object have legal value, then the member functions can maintain the objects 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
Digitech Technologies 51

Constructor
Constructors are special member functions and have the same name as the class itself. A constructor implicitly gets called when an object of that type is created. Constructors have no return value ( not even void ).

Constructors can be overloaded.


A constructor without arguments is called default constructor and a constructor with arguments is called overload constructor.

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

Digitech Technologies

52

Constructor
#include<iostream.h> #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 << " }; void main() { student s("Ravi Kumar",20); s.show(); }

Output Ravi Kumar

20

" << age << endl;

Digitech Technologies

53

Destructor
Like constructors being invoked at the time of creation, a destructor is invoked when an object is destroyed Destructors will have the same name as the class preceded by a tilde(~) No arguments No return value Cannot be overloaded Used for housekeeping job for recovering the memory allocated
class employee { : ~employee() { }
Digitech Technologies 54

Named and anonymous objects


Named object declaration syntax class_name var; // implicitly calls default constructor class_name var(value1,..); // implicitly calls overloaded constructor Unnamed (Anonymous) objects syntax class_name(); // unnamed default object class_name(v1,v2); // unnamed initialized object
Digitech Technologies 55

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

Representing a class in UML Class Diagrams


UML Class Diagram Representation of Exployee Class Notations in UML + 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

Digitech Technologies

57

Constant data members


Constant data member An object may have some fixed properties. Such properties remain unchanged throughout the life of the object. Fixed properties can be created using const type qualifier. A constant data member can be initialized with the help of a constructor. class class_name { class_name( ... ) : mem1(val1),mem2(val2) ... { } : };
Digitech Technologies 58

Constant member functions


Methods are of two types Accessor methods Accessor methods can not modify the active object state. Accessor method can be created by declaring the method as constant. data_type function_name() const { : }

Mutator methods Mutator methods can modify the active object state.

Digitech Technologies

59

Constant members
#include<iostream.h> #include<string.h> int main() { Employee e("Rajesh",1001,8900); e.show(); e.setSal(10000); e.show(); return 0; }

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=1000; } void setSal( int a ) { sal=a; } };
Digitech Technologies

Output 1001 Rajesh 8900 1001 Rajesh 10000 sal << endl;

60

Object property types


Objects may have three different types of properties Individual object property A copy of ordinary data member is given to every instance of the class. Different instances of the class may have different content Fixed property A copy of fixed data member is given to every instance of the class. Once the member initialized, it cannot be modified ( const data members ) Shared property A single copy of the data member is created and it is used by all instances of the class type ( static data members )
Digitech Technologies 61

Static data member


A static data member is used to provide shared property for the objects of the same class type. A single copy exists for all instances of the class type. All static data members must be defined in the global space. ( only in C++ )
class demo { static int num; int color; public: : };
Int demo::num=45;
Digitech Technologies 62

Size of the class demo is four bytes but not eight. Size of a class is the sum of the sizes of non-static data members

Static Member Functions


Provide a very generic functionality that doesnt require us to instantiate the class. Can be called using the class name.
class demo { void main() static int num; { int color; demo d(77),e(88); public: cout << d.getColor() << endl; demo(int a):color(a){} cout << e.getColor() << endl; static int getNum() cout << demo::getNum(); { } return num; } int getColor(){ return color; } }; Int demo::num=45;
Digitech Technologies 63

Static Members
#include<iostream.h> 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; Output } 4 6 4
Digitech Technologies 64

Memory Allocation for Classes and Objects


Member functions are assigned common memory location to all objects GetEmployeeNumber(); GetEmployeeName(); SetEmployeeNumber(int); SetEmployeeName(char*)

m_iEmpNum; char* m_pcEmpName


m_iEmpNum; char* m_pcEmpName

m_iEmpNum; char* m_pcEmpName

EmployeeThree

EmployeeTwo
Data members are assigned seperate memory locations for seperate objects

EmployeeOne

Digitech Technologies

65

this pointer
this pointer is a pointer that is automatically available in all non-static member functions of a class. It allows objects to access its own address It points to the current object, the object that invoked the method. When a member function is called, it is automatically passed an implicit argument that is a pointer to the invoking object Since static functions are not members of a class instance, this pointer cannot be used with static member functions.

Digitech Technologies

66

this pointer
A class instance have a copy of data members but not member functions. All instances of a class share a single copy of member functions. If this is the case then how a member function know which instance it is supposed to be working on. The answer lies in the fact that the a member function implicitly uses a special pointer this which a hidden parameter to the member function. this pointer points to the object that is used to invoke the member function. Within member function all member references are changed to this->member
Digitech Technologies 67

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

this pointer
#include<iostream.h> #include<string.h> void main() { radio a("Hyd"),b("Sec"),c("Mum"),d("Kol"); b.send("Hello"); }

class radio { static int count; static radio *r[50]; output char name[20]; from Hyd:Hello public: from Mum:Hello radio(char *k) from Kol:Hello { 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); } }; Write a program to create some radio stations. int radio::count=0; Show a message sent by a station is received by all radio * radio::r[50]; other stations.
Digitech Technologies 69

Different ways of class implementation


#include<iostream.h> class demo { int num; public: demo():num(0){} demo(int a):num(a){} void show() { cout<<num<<endl; } }; void main() { demo a,b(45); a.show(); b.show(); } #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; }

Digitech Technologies

70

Coding standards and naming conventions


Class names should start with capital letter - Account, Employee, Date Member variables should have 'm_' prefix followed by Hungarian notation class Date { private: int m_iDay; int m_iMonth; int m_iYear; char m_acDayOfWeek[10]; }; Instance of classes should typically have a prefix 'o' - Date oToday, oTomorrow;
Digitech Technologies 71

Coding standards and naming conventions


Names of functions: - prefix 'fn' only for C-Style functions which don't belong to any class - Names of Member functions should start with capital letter followed by capital letter for every subsequent word.

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

Coding standards and naming conventions


There are two steps to create a class A class is declared in a header file (.h file) Only one class should be declared in a single header file A corresponding .cpp file must have the implementation of the class The body of methods are defined #ifndef _EMPLOYEE_H #define _EMPLOYEE_H The class should be declared within the // Class definition here #ifndef _FILENAME_H #endif // _EMPLOYEE_H : #endif block Avoids double inclusion of same header even if included twice The block between the #ifndef and #endif is expanded only if the header has not been included already
Digitech Technologies 73

Coding standards and naming conventions


Commenting Guidelines File Header Block : All the source and header files must have the header information as shown in the format below. The code must not exceed 80 columns width
/**************************************************** * File : <filename> * Description : <description> * Author : <author> <company> * Version : <version number> * Date : <Date> * Modification log : ****************************************************/

File Footer Block : All files should have this footer at the end of the file.

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


Digitech Technologies 74

Coding standards and naming conventions


Commenting Guidelines Function or Method Header block: All functions (or methods) in the C++ files should be preceded by a comment block in the format given below:
/********************************************************* * Function: <Function Name> * Description: <Overview of the function> * Input Parameters: * <Parameter 1> <brief description> * <Parameter 2> - <brief description> * ... ... ... ... ... ... ... ... * Returns : <Return values both in case of success and * error conditions if the function returns something> *********************************************************/

Digitech Technologies

75

Coding standards and naming conventions


/******************************************************* * FileName: Employee.h * Author: E&R Department, Digitech Technologies Limited * Date: 03-Sep-2007 * Description: Declares the class Employee. *******************************************************/ #include<stdio.h> #include <malloc.h> #ifndef _EMPLOYEE_H #define _EMPLOYEE_H class Employee { private: int m_iEmpNum; char m_acEmpName[25];
Digitech Technologies 76

Coding standards and naming conventions


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

//Method to get the Employee name char* GetEmployeeName();


//method to set the Employee number void SetEmployeeNumber(int iEmpNum); //Method to set the Employee name void SetEmployeeName(char* pcEmpName);

};

#endif // _EMPLOYEE_H
/****************************************************** * End of Employee.h *******************************************************/
Digitech Technologies 77

Coding standards and naming conventions


/********************************************************** * FileName: Employee.cpp * Author: E&R Department, Infosys Technologies Limited * Date: 01-Jul-2005 * Description: Implements the class Employee. **********************************************************/ #include "Employee.h

/********************************************************** * GetEmployeeNumber * PARAMETERS: None * RETURNS: int m_iEmpNum **********************************************************/ int Employee::GetEmployeeNumber() { return m_iEmpNum; }
Digitech Technologies 78

Coding standards and naming conventions


/********************************************************** * GetEmployeeName * PARAMETERS: None * RETURNS: char* m_acEmpName **********************************************************/ const char * Employee::GetEmployeeName() { return m_acEmpName; } /********************************************************** * SetEmployeeNumber * PARAMETERS: * int iEmpNum- Employee Number * RETURNS: Nothing **********************************************************/ void Employee::SetEmployeeNumber(int iEmpNum) { m_iEmpNum=iEmpNum; }
Digitech Technologies 79

Coding standards and naming conventions


/***************************************************** * SetEmployeeName * PARAMETERS: * char* pcEmpName- Employee name (String) * RETURNS: Nothing *****************************************************/ void Employee::SetEmployeeName(char* pcEmpName) { strcpy(m_acEmpName,pcEmpName); } /***************************************************** * End of Employee.cpp *****************************************************/

Digitech Technologies

80

Method chaining(returning current obj. reference)


#include<iostream.h> 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();

Output 20 30
81

Digitech Technologies

Aggregation
Aggregation refers to a relationship where one class contains objects of another class as its members Aggregation leads to Has-A relationship

Digitech Technologies

82

C++ Dynamic Allocation Operators


The new and delete operators are used to allocate and free memory at run time. The new operator allocates memory and returns a pointer to the start of it. The delete operator frees memory previously allocated using new.

The general forms of new and delete are shown here: p_var = new type; delete p_var; Here, p_var is a pointer variable that receives a pointer to memory that is large enough to hold an item of type type.
Use malloc/realloc to allocate memory for the simple variables Use new for allocating memory for the objects
Digitech Technologies 83

C++ Dynamic Allocation Operators


The dynamic memory allocation happens on the heap. Heap is a memory space which grows or shrinks dynamically. Whenever the memory is allocated dynamically for any object, a space is allocated in the heap. This allocation remains until it is deleted (freed).

Suppose the allocated memory is not freed then this space will remain allocated even after the execution of the program. Such memory spaces could be very dangerous and may lead to the system crash due to lack of free memory.

Digitech Technologies

84

Best Practices in using new and delete operators


Never use new/delete operators in case of the simple variables; Instead use malloc and free All the memory allocations that happen within the class needs to be deallocated within the destructor. All the object pointers allocated dynamic memory must be deleted when not required.

Digitech Technologies

85

String class
#include<iostream.h> #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); Output delete s; abc s=t; welcome xyz }

}; void main() { str a("hello"),b("welcome"); a.copy("abc"); b.add(" xyz"); a.display(); b.display(); }

Digitech Technologies

86

Copy constructor
A built-in type variable can be initialized with one that is already existing variable of the same type. This is also extended to user defined types created using structures. In case of user defined types, the initialization is done using member by member copy of the structure data members. In C++ the same is applicable to variables of class types.

The default member by member copy is not sufficient in case of a class with pointer data members. The initialized object pointer member and the existing object pointer member, both point to same memory space. If the memory space is released with one of the object pointer data member, then the other object pointer member is invalid.

Digitech Technologies

87

Copy constructor
A copy constructor is automatically invoked when a new object is initialized with an existing object of the same class type. class_name::class_name( const class_name &var ); The parameter to copy constructor must be a reference of the same type.

The copy constructor of a class is called when 1)An instance of a class created from an existing instance of the same class. 2)A function is called and an argument of class type is passed by value.
If a class does not have copy constructor, then C++ provides a default copy constructor. The default copy constructor simply uses memberwise copying.
Digitech Technologies 88

Copy constructor
#include<iostream.h> #include<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(); } #include<iostream.h> #include<string.h> class str Hello { Hello 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 }

Output

Output Hello aaa

Digitech Technologies

89

Inline Functions
We can create short functions that are not actually called; rather, their code is expanded in line at the point of each invocation. This is process is somewhat similar to using a function-like macro. To make a function inline, prefix the function definition with inline class Rectangle { double Length; double Breadth ; public: inline double CalcArea() { } void Show(){ } // is also inline function void Display(); // while defining, should be decl. inline };
Digitech Technologies 90

Friend Functions
A friend function is a non-member function that is granted permission to access private members. A class may grant friendship to a global function

to another class
to a particular member function of another class

Digitech Technologies

91

Friend Functions
Global friend function #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;

/* output 12 12 */

Digitech Technologies

92

Friend Class
#include<iostream.h> class demo { int num; public: demo():num(0){} demo(int a):num(a){} friend class abc; };

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

/* Output
45 45

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

Friend Functions
#include<iostream.h> 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(); }
Digitech Technologies 94

Operator overloading
Consider the following messages on a string object. str a; a.copy(Hello); a.add(Abc); str a; a=Hello; a+Abc;

Using = and + is easy to remember and more readable than the function names like copy and add. But C++ operators cannot operate on user defined types. Operator overloading is a process of providing a user defined behavior to an operator on user defined data_type. The overloaded operators behavior remains unchanged on other data types.
Digitech Technologies 95

Operator overloading
Operator overloading rules 1) Only existing operators can be overloaded.

2) The operators . :: sizeof

.* and ?: cannot be overloaded.

3) The overloaded operators priority and associativity cannot be changed. 4) Operators can be overloaded only on user defined types.

Digitech Technologies

96

Operator overloading
An operator is overloaded by providing a special function called operator.

When the compiler see an operator on user defined type, it will search and map the statement to the special function operator provided for the operator and the operand types. Syntax: data_type operator opr_char( [ data_type p1 ] [, data_type p2 ] ) { }

Digitech Technologies

97

Operator overloading
Operators can be overloaded as member functions and also as global functions.

To be a member function, the first operand in the expression must be of the class type.
The first operand is used as active object to call the method. The other operand if exists will become formal parameter to the method. A global operator overloading is most likely made a friend function to a class. This is in order to gain access on private members of the class.
Digitech Technologies 98

Operator overloading
#include<iostream.h> #include<string.h> class str { char *s; public: str() { s=new char(0); } str(char *a) { s=new char[ strlen(a)+1 ]; strcpy(s,a); } void display() { cout<<s<<endl; } char* operator=(char *a)

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

} char* operator+(char *a) { char *t=new char[ strlen(s)+strlen(a)+1 ]; strcpy(t,s); strcat(t,a); return t; } friend char* operator+(char*,str);

};

Digitech Technologies

99

Operator overloading
char* operator+(char *a, str x) { char *t=new char[ strlen(a)+strlen(x.s)+1 ]; strcpy(t,a); strcat(t,x.s); return t; } void main() {

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 abc hello helloxyz 123hello abc

Digitech Technologies

100

Ellipsis ()
Ellipsis enables a function have variable number of arguments ( like with printf and scanf functions ). data_type function_name( ) { } Ellipsis can be accessed using va_list, va_start and va_arg defined in stdarg.h header file. First create a variable of va_list type va_list k; After creating the list variable, the list need initalized using va_start( va_list , the last known parameter name ) To extract elements from ellipsis use data_type va_arg( va_list , data_type ) Each call to va_arg returns the next element from ellipsis.
Digitech Technologies 101

Ellipsis ()
#include<iostream.h> #include<stdarg.h> void abc(int m,...) { va_list k; va_start(k,m); cout<<endl; for(int i=0;i<m;i++) cout << va_arg(k,int) << " "; } Output void main() 44 55 66 { 67 44 abc(3,44,55,66); abc(2,67,44); 23 77 55 48 34 abc(0); abc(5,23,77,55,48,34); }
Digitech Technologies 102

Operator overloading
#include<iostream.h> #include<stdarg.h> #include<stdlib.h> class array {

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

int *n,max; a[3]=600; public: for(int i=0;i<10;i++) cout << a[i] << ; array(int a,...) : max(a) } { va_list x; va_start(x,a); n=new int[max]; for(int i=0;i<max;i++) n[i]=va_arg(x,int); } int& operator[](int a) { if(a<0 || a>=max ) { cout<<error in index<<endl; exit(1); } return n[a]; }

};
Digitech Technologies 103

Operator overloading
Simulation of **, the power operator #include<iostream.h> void main() { Number a(5),b(3); cout<<a*b<<endl<<a**b<<endl; }

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

104

Type Conversions
Example for Built-in type to User-defined type conversion #include<iostream.h> #include<string.h> class demo { int num; public: demo():num(0){} demo(int a):num(a){} demo(char *k) { num = strlen(k); } void display() { cout<<num<<endl; } }; Output void main() 90 { demo a,b(23),c=b,d=45; 23 a=90; 23 a.display(); b.display(); c.display(); d.display(); 45 a=Hello; 5 a.display(); }
Digitech Technologies

105

Type Conversions
Example for User-defined to Built-in type conversion #include<iostream.h> class demo { int n1,n2; public: demo(int a,int b):n1(a),n2(b){} operator int() { return n1+n2; } }; void main() { demo d(45,55); int k; k=d; cout << k << endl; }

// 100
Digitech Technologies 106

Operator overloading
Example for User-defined to User-defined conversion #include<iostream.h> fahrenheit::operator celsius() class celsius; { class fahrenheit return (f-32.0)*5.0/9.0; { } float f; public: void main() fahrenheit():f(0){} { fahrenheit(float a):f(a){} celsius a,b(30); void display(){ cout<<f<<endl; } fahrenheit c,d(100); operator celsius(); }; a=(celsius)d; c=(fahrenheit)b; class celsius { a.display(); float c; b.display(); public: c.display(); celsius():c(0){} d.display(); celsius(float a):c(a){} } void display(){ cout<<c<<endl; } operator fahrenheit() { return c*9.0/5.0 + 32.0; } };
Digitech Technologies 107

Inheritance
The process of deriving a new class from an existing class is called Inheritance The old class is referred to as the base class and the new class is called the derived class or subclass. Through Inheritance, C++ strongly supports the idea of Reusability. That is making use of the existing features to create the new feature. All the objects in this world come under some kind of classification. Inheritance allows the creation of hierarchical classification. For example, the bike Yamaha is a part of the class Two Wheeler which is again a part of the class Vehicle.

Digitech Technologies

108

Inheritance

Digitech Technologies

109

Inheritance
Generalization and Specialization Generalization and Specialization are associated with the concept of Inheritance The Trainee class derives the Employee class Employee class is a generalization of Trainee class Trainee class is a specialization of the Employee class

Digitech Technologies

110

Inheritance
Inheritance Relationship is a relation exists between the derived class and base class. Trainee is an Employee

Employee

Trainee

Digitech Technologies

111

Inheritance
Creating derived classes The general format of deriving the properties from one class to another class is : class derived-class-name : [visibility-mode] base-classname [,] { // members of derived class }; Here, the visibility mode is optional and , if present, may be either private , public or protected.

The default visibility mode is private.


Visibility mode specifies whether the features of the base class are privately derived or publicly derived.
Digitech Technologies 112

Inheritance
Types of Inheritance based on structure

Digitech Technologies

113

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

Public

private public protected

(inaccessible) public protected

Protected

private public protected

(inaccessible) protected protected


114

Digitech Technologies

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 dont want to access those members thru the object of the class. Those members come under protected access specifier.

In other words, protected members are private to all, but public to its derived classes.

Digitech Technologies

115

Inheritance
Protected Members Advantages: Derived classes can modify values directly Slight increase in performance; Avoids set/get function call overhead

Disadvantages:
No validity checking - Derived class can assign illegal value Implementation dependent - Derived class member functions more likely dependent on base class implementation - Base class implementation changes may result in derived class modifications resulting in Fragile (brittle) software
Digitech Technologies 116

Inheritance
Constructors in the Base and Derived Classes An instance of a derived class contains the data members inherited from its base class and its own data members. To initialize the members, compiler first calls the base class constructor to initialize base class members, and then calls derived class constructor to initialize the derived class members. The derived class constructor must tell the Compiler which base class constructor to use for base class member initialization. This is provided by using base class parameter list: derive_class( a1,a2,a3, ) : base_class( p1,p2, ) , mem_init { } If base class parameter list is not provided, then compiler automatically calls the base class default constructor.
Digitech Technologies 117

Inheritance
#include<iostream.h> class base { int num; public: base():num(0){} base(int k):num(k){} void show() { cout<<num<<endl; }; void main() { derive d(45); d.show(); d.display();

class derive : public base { int num; public: derive():num(0){} derive(int k):base(k/2),num(k){} void display() { cout<<num<<endl; } };
Digitech Technologies

/* output 22 45 */

118

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.

Digitech Technologies

119

Inheritance
#include<iostream.h> class base { int num; public: base():num(0){} base(int k):num(k){} void show() { cout<<num<<endl; }; void main() { derive d(45); d.base::show(); d.show();

class derive : public base { int num; public: derive():num(0){} derive(int k):base(k/2),num(k){} void show() { cout<<num<<endl; } };
Digitech Technologies

/* output 22 45 */

120

Inheritance
Point2D and Point3D ( without 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; } }; void main() { threeD td(56,34,90); td.display(); cout<<endl; td.setx(51); td.display(); } 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; } };

Digitech Technologies

121

Inheritance
Point2D and Point3D ( with 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; } }; void main() { threeD td(56,34,90); td.display(); cout<<endl; td.setx(51); td.display(); } 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; }

};

Digitech Technologies

122

Inheritance
Assignment Operator overloading for a Derived Class Like Copy Constructor of derived class that explicitly calls Copy Constructor of base class, assignment operator overloading of derived class must explicitly call base class assignment operator function. derive derive::operator=(int a) { base::operator=(a); // calling base assignment operator overloading : : }

Digitech Technologies

123

Inheritance

Copy Constructors of Base and Derived Classes When a new instance of derived class created using derive class copy constructor, the Compiler does not automatically call the base class copy constructor. Instead of the base class copy constructor, the compiler calls default constructor of the base class. This problem can be overcome by an explicit call to base class copy constructor from derive class copy constructor.

Digitech Technologies

124

Inheritance
#include<iostream.h> 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 ~derive(){ cout<<from derive destructor\n; } }; void main() { derive a; derive b=a; }
Digitech Technologies

Output: from base default from derive default from base copy const from derive copy const from derive destructor from base destructor from derive destructor from base destructor

const\n"; }

125

Inheritance
Multiple Inheritance C++ allows a class derived from more than one base or parent classes. The derived class will have all the members of the base classes. The base classes may have members with same name. Use base class name and scope resolution operator ( :: ) to avoid ambigious member reference.

Virtual Inheritance
Suppose a class DERIVE is derived from two different base classes BASE1 and BASE2, which in turn are derived from the same base class COMMON_BASE. It is clear that the DERIVE class will have two copies of COMMON_BASE class members. Virtual inheritance can solve the above problem. When a class derives several times from the same virtual base class, this derive class will have only one copy of the base class.
Digitech Technologies 126

Inheritance
#include<iostream.h> class common_base { 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

Digitech Technologies

127

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

virtual inheritance

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


128

Digitech Technologies

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<< } char getgrade(){ return grade; }
Digitech Technologies 129

<<grade<< ;

};

Inheritance - Example
class manager : public employee { int sal;

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

};

Digitech Technologies

130

Inheritance - Example
class wage_employee : public employee { int hours,rate;

public:
wage_employee(){} wage_employee(char *a,int b,int c):employee(a,C), hours(b),rate(c){} void display() { employee::display(); cout<<hours<< <<rate<< ; } int pay(){ return hours*rate; } protected: wage_employee(char *a,int b,int c,char d):employee(a,d), hours(b),rate(c){}

};

Digitech Technologies

131

Inheritance - Example
class sales_person : public wage_employee { int comm,sales; public: sales_person(){} sales_person(char *a,int b,int c,int d,int e):wage_employee(a,b,c,B), comm(d),sales(e){} void display() { wage_employee::display(); } cout<<comm<< <<sales<< ;

};

int pay() { return wage_employee::pay()+( sales>100 ? comm : 0 ); }

Digitech Technologies

132

Inheritance - Example
void main() { manager m[50]; wage_employee w[50]; sales_person s[50]; char ch,name[20]; int mmax,smax,wmax,sal,hours,rate,comm,sales; mmax=wmax=smax=0; while( ch!='q' ) { cout<<"\nwage employee cin>>ch; cin.get();

sales person

manager

quit ";

if(ch=='w' || ch=='s' || ch=='m') { cout<<"Enter name "; cin.getline(name,20);


Digitech Technologies 133

Inheritance - Example
if(ch=='m') { cout<<"Enter salary "; cin>>sal; cin.get(); } if(ch=='w' || ch=='s') { cout<<"Enter hours "; cin>>hours; cout<<"Enter rate "; cin>>rate; cin.get(); m[mmax]=manager(name,sal); mmax++;

if(ch=='w') { w[wmax]=wage_employee(name,hours,rate); wmax++; }


Digitech Technologies 134

Inheritance - Example
if(ch=='s') { cout<<"Enter comm "; cin>>comm; cout<<"Enter sales "; cin>>sales; cin.get(); s[smax]=sales_person(name,hours,rate,comm,sales); smax++;

Digitech Technologies

135

Inheritance - Example
int i; long 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 identical except the object references This is because the data is stored in three different arrays
136

Digitech Technologies

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 cin>>ch; cin.get();

sales person

manager

quit ";

if(ch=='w' || ch=='s' || ch=='m') { cout<<"Enter name "; cin.getline(name,20);


Digitech Technologies 137

Inheritance - Example
if(ch=='m') { cout<<"Enter salary "; cin>>sal; cin.get(); e[max]=new manager(name,sal); max++;

} if(ch=='w' || ch=='s') { cout<<"Enter hours "; cin>>hours; cout<<"Enter rate "; cin>>rate; cin.get(); if(ch=='w') { e[max]=new wage_employee(name,hours,rate); max++; }
Digitech Technologies 138

Inheritance - Example
if(ch=='s') { cout<<"Enter comm "; cin>>comm; cout<<"Enter sales "; cin>>sales; cin.get(); e[max]= new sales_person(name,hours,rate,comm,sales); max++;

Digitech Technologies

139

Inheritance - Example
int i; for(i=0;i<max;i++) { switch( e[i]->getgrade() ) { case 'A': ((manager*)e[i])->display(); cout<<endl; break; case 'B': ((sales_person*)e[i])->display(); cout<<endl; break; case 'C': ((wage_employee*)e[i])->display(); cout<<endl; break; } } The code repetition problem still exists

Digitech Technologies

140

Polymorphism
Is a Greek word, which means one name, multiple forms. Is the ability of objects to respond differently to the same message. The kind of response is dependent on the data types used in a given instance. Allows objects having different internal structure to share the same external interface.

Digitech Technologies

141

Polymorphism
Polymorphism - Binding Binding refers to the process of linking a procedure call to the code to be executed in response of the call. Are of two types. Static binding or Early binding and Dynamic binding or Late binding. In Static binding the code associated with a given procedure call is resolved during compiler time. In Dynamic binding the code associated with a given procedure call is resolved during run-time.

Digitech Technologies

142

Polymorphism
#include<iostream.h> #include<string.h> class class class class employee ... manager : public employee wage_employee : public employee ... sales_person : public wage_employee ...

void main() { employee *e=new sales_person("Ravi Kumar",5,90,500,102); e->display(); cout<<endl; ((sales_person*)e)->display(); cout<<endl; output Ravi Kumar Ravi Kumar
Digitech Technologies

B B 5

90

500

102
143

Polymorphism
#include<iostream.h> #include<string.h> class class class class employee { virtual void display(){ } ... manager : public employee wage_employee : public employee ... sales_person : public wage_employee ...

void main() { employee *e=new sales_person("Ravi Kumar",5,90,500,102); e->display(); cout<<endl; ((sales_person*)e)->display(); cout<<endl; output Ravi Kumar Ravi Kumar
Digitech Technologies

B 5 B 5

90 90

500 500

102 102
144

Polymorphism
Virtual functionsDynamic Polymorphism Instead of making type casting the pointer the same effect can be got by defining the overridden methods as virtual in the base class class employee { virtual void display(); The base class pointers can now be pointing to derived types employee *e=new sales_person(); e->display(); This actually invokes the sales_person class method This determination of which version of the overridden method to invoke happens at run time. This is known as Dynamic Binding
Digitech Technologies 145

Polymorphism
class employee { : public: employee(){} employee(){} virtual void display(){ } }; : Compiler Error: : 'pay' : is not a member of 'employee' void main() { employee *e=new sales_person("Ravi Kumar",5,90,500,102);

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

Digitech Technologies

146

Polymorphism
class employee { : public: employee(){} employee(){} virtual void display(){ } virtual int pay(){ return 0; } }; Output : Ravi Kumar B 5 90 500 102 950 : void main() { employee *e=new sales_person("Ravi Kumar",5,90,500,102); e->display(); cout<<e->pay()<<endl;
Digitech Technologies 147

Polymorphism
class employee { : virtual void display(){ } manager pay virtual int pay(){ return 0; } }; class manager : public employee { : public: Output // int pay(){ return sal; } Ravi Kumar A 19000 0 }; : void main() { employee *e=new manager("Ravi Kumar",19000); e->display(); cout<<e->pay()<<endl; }
Digitech Technologies 148

Polymorphism
Abstract class At times we may not want the objects of the base class to be created at all If one of the methods of the base class is made pure virtual function then that class will become abstract. Example: virtual int pay()=0; No objects of abstract class can be created. But pointers to abstract class can be created Abstract classes act like an interface.
Digitech Technologies 149

Polymorphism
class employee { : virtual void display(){ } virtual int pay()=0; }; class manager : public employee { : public: Compiler Error: // int pay(){ return sal; } 'manager' : cannot instantiate abstract class }; : void main() { employee *e=new manager("Ravi Kumar",19000); e->display(); cout<<e->pay()<<endl; }
Digitech Technologies 150

Polymorphism
class employee { : virtual void display(){ } virtual int pay()=0; }; class manager : public employee { : public: Output: int pay(){ return sal; } Ravi Kumar A 19000 19000 }; : void main() { employee *e=new manager("Ravi Kumar",19000); e->display(); cout<<e->pay()<<endl; }
Digitech Technologies 151

Polymorphism
#include<iostream.h> class shape { public: virtual int area()=0; }; class circle : public shape { int r; public: circle(int a):r(a){} int area() { return 22.0/7.0*r*r; } }; class square : public shape { int s; public: square(int a):s(a){} int area() { return s*s; } };
Digitech Technologies

Shape Example

152

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

Polymorphism
General purpose sort Example #include<iostream.h> #include<string.h> class sort { public: class sortable static void bubble(sortable **e,int max) { { public: sortable *t; virtual int compare(sortable*)=0; int i,k; }; for(i=0;i<max-1;i++) for(k=0;k<max-i-1;k++) if( e[k]->compare(e[k+1]) >0 ) { t=e[k]; Any user-defined types can e[k]=e[k+1]; be sorted using the sort e[k+1]=t; } class, provided the class } defines compare method. };
Digitech Technologies 154

Polymorphism
class employee : public sortable General purpose sort Example { char name[20]; int sal; public: employee(){} employee(char *a,int b):sal(b) { strcpy(name,a); } void show() { cout<<name<<" --- "<<sal<<endl; } int compare(sortable *k) { employee *e=(employee *)k; return sal-e->sal; } };

Digitech Technologies

155

Polymorphism
#define MAX 5 void main() { employee *e[MAX]={ General purpose sort Example

new new new new new

employee("Ravi",9000), employee("Giri",12000), employee("Sham",8000), employee("Sing",10000), employee("Neha",11000)

};

sort::bubble((sortable**)e,MAX); for(int i=0;i<MAX;i++) e[i]->show();

Output Sham --- 8000 Ravi --- 9000 Sing --- 10000 Neha --- 11000 Giri --- 12000
Digitech Technologies 156

Polymorphism
#include<iostream.h> Virtual Destructor

class base { public: ~base(){ cout<<"from base destructor\n"; } }; class derive : public base { public: ~derive(){ cout<<"from derive destructor\n"; } }; void main() { base *d=new derive(); delete d; } Output from base destructor

Digitech Technologies

157

Polymorphism
#include<iostream.h> Virtual Destructor

class base { public: virtual ~base(){ cout<<"from base destructor\n"; } }; class derive : public base { public: ~derive(){ cout<<"from derive destructor\n"; } }; void main() { base *d=new derive(); delete d; } Output from derive destructor from base destructor

Digitech Technologies

158

Exception Handling
An Exceptional condition is an event that occurs during the execution of C++ program (runtime anomalies) causing a program to interrupt.

Examples: Out-of-bound array subscript, arithmetic overflow or underflow, division by zero, out of memory, invalid function parameter, etc.,
An exceptional condition may be either an unexpected error or an expected error at an unpredictable time.

Digitech Technologies

159

Exception Handling
The process of detecting and taking an appropriate action for exceptions is referred to exception handling. Exception handling involves the following steps. (1) Find the error (try), (2) Inform that an error as occurred (throw), (3) Receive the error information (catch) & (4) Take corrective actions (Handle) The C++ exception handling mechanism is built upon three keywords namely try, throw and catch.

Digitech Technologies

160

Exception Handling
The keyword try is used to preface a block of statements which may generate exceptions. This block of statements is known as try block.

The throw statement is used to inform that an exception has occurred. It is coded within the try block.
The keyword catch is used to preface a block called catch block to receive and handle the exception informed by the throw statement. The catch block must immediately follow the try block that throws the exception.

Digitech Technologies

161

Exception Handling
Syntax for try and catch blocks

: try {

} catch (type argument) { : } :

: if( ) throw exception; :

Digitech Technologies

162

Exception Handling
When the try block throws an exception, the program control leaves the try block and enters the catch block. If the type of the object thrown matches the argument type in the catch statement, then the catch block is executed otherwise the program is aborted with the help of the abort ( ) function. If no exception is thrown, the control goes to the statement immediately following the catch block.

Digitech Technologies

163

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

Simple example

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 {

Raising exception from within try block and from outside try block

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


Digitech Technologies 165

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

} catch(char *e) { cout<<e<<endl; }

Raising exception from within try block and from outside try block

cout<<"\ntry more (y/n) "; cin>>ch; cin.get();


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

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

Digitech Technologies

166

Exception Handling
It is possible to have multiple catch blocks following a try block to handle all possible exceptions. In some situations, we may not be able to anticipate all possible types of exceptions. In such cases we can catch all exceptions using the following form of catch statement. Syntax to catch all types of exceptions

catch() // catch with ellipsis { : }

Digitech Technologies

167

Templates
Is mechanism provided to implement the concept of generic programming. Allows programmers to create a family of similar classes or functions. Eliminate code duplication for different types and thus make the software development easier and more manageable. Are to be defined with parameters that would be replaced by a specified data type at the time of actual use of the class or function.

Digitech Technologies

168

Templates
Templates are example code for compiler, which generates actual code with the help of the template. Templates are of two types Function templates: Function templates are also known as parameterized or generic functions. Class templates: Class templates are also known as parameterized or generic types. Function Template syntax: template< class T [ , class M , ..... ] > data_type function_name( data_type var1, ... ) { data_type v1,v2; // local variables }
Digitech Technologies 169

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

Function Template Example

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; }
Digitech Technologies 170

Output 20 x 88.34 welcome

Templates
#include<iostream.h> template<class T> class demo { T data; public: demo(){} demo(T a):data(a){} void display() { cout << data << endl; }

Class Template Example

Output 67 hello -1.07374e+008

};

void main() { demo<int> a(67); demo<char*> b(hello); demo<float> c; } a.display(); b.display(); c.display();
Digitech Technologies

171

Templates
General Purpose Sorting Template Function
#include<iostream.h> #include<string.h> template<class T> void bubble(T **e,int max) { T *t; int i,k; for(i=0;i<max-1;i++) for(k=0;k<max-i-1;k++) if( e[k]->compare(e[k+1]) > 0 ) { t=e[k]; e[k]=e[k+1]; e[k+1]=t; }

Digitech Technologies

172

Templates
General Purpose Sorting Template Function
class employee { char name[20]; int sal; public: employee(){} employee(char *a,int b):sal(b) { strcpy(name,a); } void show() { cout<<name<<" --- "<<sal<<endl; } int compare(employee *k) { return sal-k->sal; } };
Digitech Technologies 173

Templates
General Purpose Sorting Template Function
#define MAX 5 void main() { employee *e[MAX]={

new employee("Ravi",9000), new employee("Giri",12000), new employee("Sham",8000), new employee("Sing",10000), new employee("Neha",11000)

};

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

Output Sham --- 8000 Ravi --- 9000 Sing --- 10000 Neha --- 11000 Giri --- 12000
174

Digitech Technologies

Templates
Class Template : Array Example
#include<iostream.h> #include<stdarg.h> #include<stdlib.h> template<class T,int s> class array { T *n; int max; public: array(int a,...) : max(a) { va_list x; va_start(x,a); n=new T[max]; for(int i=0;i<max;i++) n[i]=va_arg(x,T);

Digitech Technologies

175

Templates
Class Template : Array Example
T& operator[](int a) { a=a-s; if(a<0 || a>=max ) { cout<<"error in index"<<endl; exit(1); } return n[a]; } Output 56 7 89 45 33 8 9 32 11 30 Hello Welcome

};

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

Digitech Technologies

176

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> { };
Digitech Technologies 177

void main() { demo<int> a(45); demo<char*> b("Hello"); demo<float> c; a.show(); b.show(); c.show();

Output 45 Hello -1.07374e+008

IO Streams
Streams are channels of communication between programs and source/destination of data A stream is either a source of bytes or a destination for bytes. Provide a good abstraction between the source and destination Abstract away the details of the communication path from I/O operation Streams hide the details of what happens to the data inside the actual I/O devices. Streams can read/write data from/to blocks of memory, files etc...

Digitech Technologies

178

IO Streams

Reads
Source Stream Program

Writes Program Stream Destination

Digitech Technologies

179

IO Streams
The stream classes are defined in iostream.h and fstream.h header files. The stream classes are of two types. Console streams and File streams. ios

istream

ostream

iostream ifstream fstream


Digitech Technologies

ofstream
180

IO Streams
A stream property can be set by using formatting flags. Formatting flags are enums defined in ios class. The formatting flags are

ios::dec ios::oct ios::hex ios::uppercase


ios::left ios::right ios::showpos ios::showbase

output number format is decimal output number format is octal output number format is hexadecimal hexadecimal alphabets ( a-f ) in uppercase
left adjust data in a field width right adjust data in a field width + prefixed to a positive value prefix the base indicator no_prefix --- decimal ex: 65 0 prefix --- octal ex: 065 0x prefix --- hexadecimal ex: 0x65
Digitech Technologies 181

IO Streams
Methods for setting/resetting formatting flags setf(long flag) sets specified flag without affected other flags unsetf(long flag) resets specified flag without affected other flags #include<stdio.h> #include<iostream.h> void main() { printf("%x %d\n",65,70); cout.setf(ios::hex); cout<<65<<" "; cout.unsetf(ios::hex); cout.setf(ios::dec); cout<<70<<endl;
Digitech Technologies

Output 41 70 41 70

182

IO Streams
Method for setting field width width(int) :the width set is valid only for the next argument printed.
#include<stdio.h> #include<iostream.h> void main() { printf("*%-4d*\n*%10d*\n",65,70);

cout<<'*'; cout.width(4); cout.setf(ios::left); cout<<65<<'*'<<endl; cout<<'*'; cout.width(10); cout.setf(ios::right); cout.unsetf(ios::left); cout<<70<<'*'<<endl;


Digitech Technologies

Output

*65 * * 70* *65 * * 70*


183

IO Streams
Method for setting padding character : fill(char) padding character is a character used to fill unused spaces in a #include<iostream.h> void main() { cout.width(4); cout.setf(ios::left); cout.fill('*'); cout<<65<<endl; cout.width(10); cout.setf(ios::right); cout.unsetf(ios::left); cout.fill('-'); cout<<70<<endl;
Digitech Technologies

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

184

IO Streams
Unformatted input methods char get() get() is same as getchar function in C get(char *dest, int max, char termination =\n) gets input from buffer and stores at dest. The characters input is either max or upto the termination character. getline(char *dest, int max, char=\n) getline() is same as get(...) except it extracts data from buffer including the termination character. read(char *dest, int max) read() gets max characters from input buffer. It does not have any termination character.
Digitech Technologies 185

IO Streams
#include<iostream.h> void main() { char s[80]; cout<<"Enter name : "; cin>>s; } cout<<s<<endl; } #include<iostream.h> void main() { char s[80]; cout<<"Enter name : "; cin.get(s,80); cout<<s<<endl;

Output Enter name : Ravi Kumar Ravi

Output Enter name : Ravi Kumar Ravi Kumar

Digitech Technologies

186

IO Streams
#include<iostream.h> void main() { char s1[80],s2[80]; cout<<"Enter name : "; //cin.get(s1,80); //cin.get(); cin.getline(s1,80); cout<<"Enter name : "; cin.get(s2,80); } cout<<s1<<endl<<s2<<endl;
Output Enter name : ravi Enter name : giri ravi giri

Digitech Technologies

187

IO Streams
Read method is used to read a random access file #include<iostream.h>

void main() { char s[80];


cout<<"Enter name : "; cin.read(s,80); } cout<<s<<endl;

Digitech Technologies

188

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

IO Streams
Customizating cin and cout objects #include<iostream.h>

class employee { char name[20]; int sal; friend istream& operator>>(istream &,employee &); friend ostream& operator<<(ostream &,employee &); };
istream& operator>>(istream &k,employee &m) { cout<<"Enter name : "; cin.getline(m.name,20); cout<<"Enter sal : "; cin>>m.sal; return k; }
Digitech Technologies

190

IO Streams
Customizating cin and cout objects ostream& operator<<(ostream &k,employee &m) { cout<<m.name<<" --- "<<m.sal<<endl; return k; } void main() { employee e; cin>>e; cout<<e; Output Enter name : Ravi Kumar Enter sal : 9000 Ravi Kumar --- 9000

Digitech Technologies

191

IO Streams
cin customization #include<iostream.h> istream& operator>>(istream &a,void *b) { cout<<(char*)b; return a; } void main() { int a,b;

cin >> (void*)Enter a number >> a >>(void*)ENTER A NUMBER >> b; cout << a+b << endl;
}
Digitech Technologies 192

IO Streams
File Streams Sequential access file : In sequential file records can only be read sequentially. To read records randomly, the address of Nth record should known. Sequential file record size varies, that is why the address of Nth record can not be found. Random access file : In random access files records can be read randomly. Random records size is fixed, that is why address of Nth record can be found. ( rec_number - 1 ) * ( size of record )
Digitech Technologies 193

IO Streams
File stream classes are defined in fstream.h header file.
Ifstream ifstream() ifstream(char *fname,int mode=ios::in) open(char *fname,int mode=ios::in) close(); long tellg() seekg(long position,int seek_direction=ios::beg) ad ) ofstream ofstream() ofstream(char *fname,int mode=ios::out) open(char *fname,int mode=ios::out) close(); long tellp() seekp(long position,int seek_direction=ios::beg) fstream fstream() fstream(char *fname,int mode) open(char *fname,int mode) ...
Digitech Technologies 194

IO Streams
File Open Modes ios::in file opened to input ios::out file opened to output ios::app file opened to append records File Seek Direction ios::beg set file pointer from beginning of the file ios::cur set file pointer from current position of the file ios::end set file pointer from end of the file File Status Methods int good() returns true value if the last operations successful int bad() returns true value if last operation failed int eof() returns true value if end of file is reached

Digitech Technologies

195

IO Streams
Appends a record to emps.dat sequential file #include<fstream.h> void main() { char name[20]; int sal; cout << Enter emp name ; cin.getline(name,20); cout << Enter salary ; cin >> sal; ofstream x(emp.dat,ios::app); if( x.bad() ) { cout << error\n; x << name << , << sal << endl; }
Digitech Technologies 196

return 1;

IO Streams
Reads records from emps.dat and prints them on screen #include<fstream.h> void main() { char name[20]; int sal; ifstream x(emp.dat); if( x.bad() ) { cout << error\n; return 1; } while( !x.eof() ) { x.getline(name,20,,); x >> sal; if( x.good() ) cout << name << ----- << sal; } x.close(); }
Digitech Technologies 197

IO Streams
Appends a record to empr.dat random file #include<fstream.h> struct record { char name[23]; int sal; }; void main() { record r; cout << Enter emp name ; cin.getline(r.name,23); cout << Enter salary ; cin >> r.sal; ofstream x(empr.dat,ios::app); if( x.bad() ) { cout << error\n; return 1; } x.write( (char*)&r,sizeof( r )); }
Digitech Technologies 198

IO Streams
Reads records randomly #include<fstream.h> struct record { char name[23]; int sal; };

void main() { record r; int rec,max; ifstream x(empr.dat); if( x.bad() ) { cout << error\n; x.seekg(0,ios::end); max=x.tellg()/sizeof( r );
return 1; }

Digitech Technologies

199

IO Streams
rec=1; while( rec>0 ) { cout << enter a record number 1 to << max << : ; cin >> rec; cin.get(); if(rec>=1 && rec<=max) { x.seekg( (rec-1)*sizeof( r ),ios::beg ); x.read( (char*)&r,sizeof( r ) ); cout << r.name << ---- << r.sal << endl; } else cout << invalid record number\n; } x.close(); }
Digitech Technologies 200

IO Streams
Manipulators Manipulators are objects that can be used within the chain of insertion and extraction operators. Manipulators are used to set stream attributes from within the chain of << or >> operators. Manipulators are of two types Built-in manipulators without arguments dec - sets output format to decimal oct - sets output format to octal hex - sets output format to hexadecimal endl - generates newline sequence

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

IO Streams
Built-in manipulators with single argument Method Manipulator -------------------------------------------setf(long) setiosflags(long) unsetf(long) resetiosflags(long) width(int) setw(int) fill(char) setfill(char) --------------------------------------------The single argument manipulators are defined in iomanip.h header file.

Digitech Technologies

202

IO Streams
#include<iostream.h> #include<iomanip.h> void main() { cout << setw(10) << setiosflags(ios::left) << setfill('*') << 65 << endl << setw(20) << resetiosflags( ios::left ) << setiosflags(ios::right) << setfill('-') << 65 << endl; }

Output 65******** ------------------65


Digitech Technologies 203

IO Streams
User-Defined Manipulator #include<iostream.h> class set { public: int w,j; char f; set(int a,int b,char c):w(a),j(b),f(c){} }; ostream& operator<<( ostream &a,set b ) { a.width( b.w ); a.fill( b.f ); if( b.j ) {
Digitech Technologies 204

IO Streams
a.setf(ios::right); a.unsetf(ios::left);

} else { a.setf(ios::left); a.unsetf(ios::right); } return a;

void main() { cout << set(10,0,'*') << 65 << endl << set(20,1,'-') << 65 << endl; }
Digitech Technologies

Output 65******** ------------------65


205

Smart Pointers
Take care of automatic initialization and cleanup Take care of dangling pointers Keep track of dynamically allocated objects shared by multiple owners

Digitech Technologies

206

Smart Pointers
void abc() { demo *p(new demo); p->doSomething(); delete p; } void abc() { demo *p; try { p=new demo; p->doSomething(); delete p; } catch(){} void abc() { auto_ptr<demo> *p(new demo); p->doSomething(); }

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

Digitech Technologies

207

Smart Pointers( Simple Example )


#include<iostream.h> class demo { int num; int rc; public: demo():num(0),rc(0){} demo(int k):num(k),rc(0){} void show(){ cout<<num<<'-'<<rc<<endl; } void addReference(){ rc++; } int removeReference() { if(rc>0) rc--; return rc; } };
Digitech Technologies 208

Smart Pointers( Simple Example )


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

RTTI - Run-Time Type Identification


Knowing the type of identifiers at run-time typeid(expr.) is used to know the type of expression at run-time typeid Operator typeid( type-id ) or typeid( expression ) The typeid operator allows the type of an object to be determined at run-time. The result of a typeid expression is a const type_info&. The value is a reference to a type_info object that represents either the type-id or the type of the expression, depending on which form of typeid is used.
Digitech Technologies 210

RTTI - Run-Time Type Identification


type_info Class The type_info class describes type information generated within the program by the compiler. Objects of this class effectively store a pointer to a name for the type. The type_info class also stores an encoded value suitable for comparing two types for equality or collating order. The encoding rules and collating sequence for types are unspecified and may differ between programs. class type_info { public: virtual ~type_info(); int operator==(const type_info& rhs) const; int operator!=(const type_info& rhs) const; const char* name() const; const char* raw_name() const; private: ...};
Digitech Technologies 211

RTTI - Run-Time Type Identification


#include<iostream.h> #include<typeinfo.h> For RTTI make settings as shown: Project > Settings > C/C++ tab > Category - C++ Language > Check Run-Time Type information

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

Digitech Technologies

212

RTTI - Run-Time Type Identification


class wage_employee : public employee { public: void show() { cout<<"from wage_employee\n"; } }; void main() { employee *e=new manager; if( typeid(*e) == typeid(manager) ) cout << "manager" << endl; Output
Digitech Technologies

manager

213

Standard Template Library ( STL )


The STL is a generic library that provides solutions to managing of data with modern and efficient algorithms Advantages of the STL - You dont have to write your classes and algorithms - You dont have to worry about allocating and freeing memory - Reduces your code size because STL uses template - Easy to use and easy to learn

Digitech Technologies

214

Standard Template Library ( STL )


STL Components Containers: used to manage collections of objects of a certain kind ex: vector, queue, list Algorithms: functions for processing the elements of a container ex: function to copy, sort and search container Iterators: are used to step through the elements of containers ex: iterator to move through a list

Digitech Technologies

215

Standard Template Library ( STL )


STL Containers - Sequential containers: are ordered collections in which each element has a certain position ex: vector, list, deque - Associative containers: are sorted collections in which the actual position of an element depends on its value due to a certain sorting criterion ex: set, map, multiset, multimap

Digitech Technologies

216

Standard Template Library ( STL )


STL Containers set/multiset

vector

Map/multimap deque

list

Digitech Technologies

217

Standard Template Library ( STL )


#include<iostream> #include<vector> using namespace std; void main() { vector<int> v; int i; v.push_back(45); v.push_back(78); v.push_back(59); v.push_back(22); v.push_back(14); vector example

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


v.at(2)=88;
Digitech Technologies 218

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;
Digitech Technologies 219

vector example

Output 45 59 45 59 45 59 45 59

22 88 88 78

78 14 78 14 78 14 14

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

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


Digitech Technologies

Output 14 78 45 59 22

220

Standard Template Library ( STL )


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

l.push_back(45); l.push_back(59); l.push_back(22); l.push_front(78); l.push_back(14); list<int>::iterator it=l.begin(); for(int i=0;i<l.size();i++) { cout<<*it<<" "; it++; }
Digitech Technologies 221

Standard Template Library ( STL )


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

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

Digitech Technologies

222

Standard Template Library ( STL )


STL - Associative Containers - Set: A set is a collection where elements are sorted according to their own values - Multiset: A multiset is the same as set except that duplicates are allowed - Map: A map contains elements that are key/value pairs. Elements are sorted on keys. Each key may occur only once. - Multimap: A multimap is the same as map, except that duplicates are allowed ( multiple elements may have the same key
Digitech Technologies 223

Standard Template Library ( STL )


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

set example

Output 14 22 45 59 78
224

Standard Template Library ( STL )


set example #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; } };
Digitech Technologies 225

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++) Output { Ganesh 2200 it->show(); Giri 8900 it++; Kiran 7700 } Ravi 6700 Sham 4500
Digitech Technologies 226

set example

Standard Template Library ( STL )


#include<iostream> #include<map> using namespace std; void main() { map<int,int> m; int i; m.insert( m.insert( m.insert( m.insert( m.insert( pair<int,int>(1,10) pair<int,int>(2,20) pair<int,int>(0,30) pair<int,int>(3,40) pair<int,int>(4,50) ); ); ); ); ); Output 30 10 20 40 50 map example

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


Digitech Technologies 227

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

} /* Output 12 34 36 44 44 56 78 78 90 95 */
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}; int *p=find(n,n+10,34); } /* Output Position:4 */ cout<<"Position:"<<p-n<<" Value:"<<*p<<endl; find example

Value:34
Digitech Technologies 229

Standard Template Library ( STL )


Function Objects - A function object encapsulates a function in an object for use by other components. - An object of any class or struct that overloads the function call operator, operator() Passing a function object to an algorithm is similar to passing a pointer to a function, but there are some important differences - pass function objects to algorithms at compile time - increases efficiency, by inlining the corresponding call

Digitech Technologies

230

Standard Template Library ( STL )


#include<iostream> #include<algorithm> using namespace std; class abc { public: bool operator()(int x,int y) const { return x>y; } }; Function Object Example

void main() { int n[10]={56,44,78,90,34,12,36,78,95,44}; int i;


Digitech Technologies 231

Standard Template Library ( STL )


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

} Output 12 34 36 44 44 56 78 78 90 95 95 90 78 78 56 44 44 36 34 12 95 90 78 78 56 44 44 36 34 12

Digitech Technologies

232

Das könnte Ihnen auch gefallen