object oriented - himpub.com · unit – i introduction to oops: need of object oriented...

16

Upload: others

Post on 14-Mar-2020

17 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs
Page 2: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

Object OrientedProgramming with

C++(As per the Syllabus 2012-13 of Mumbai University for B.Sc. – IT, Semester III)

Mr. Hiren Jayantilal DandAssistant Professor (Co-ordinator of B.Sc. IT and M.Sc. IT),

Parle Tilak Vidyalaya Association’sMulund College of Commerce (Mulund).

Ms. Sandhya P. PandeyAssistant Professor,

The SIA College of Higher Education, Dombivli (E).

Ms. Nandini V. GaikwadAssistant Professor,

The SIA College of Higher Education, Dombivli (E).

ISO 9001:2008 CERTIFIED

Page 3: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

© AuthorsNo part of this publication may be reproduced, stored in a retrieval system, or transmitted in any form or by anymeans, electronic, mechanical, photocopying, recording and/or otherwise without the prior written permission of thepublisher.

First Edition : 2016

Published by : Mrs. Meena Pandey for Himalaya Publishing House Pvt. Ltd.,“Ramdoot”, Dr. Bhalerao Marg, Girgaon, Mumbai - 400 004.Phone: 022-23860170/23863863, Fax: 022-23877178E-mail: [email protected]; Website: www.himpub.com

Branch Offices :

New Delhi : “Pooja Apartments”, 4-B, Murari Lal Street, Ansari Road, Darya Ganj,New Delhi - 110 002. Phon e: 011-23270392, 23278631; Fax: 011-23256286

Nagpur : Kundanlal Chandak Industrial Estate, Ghat Road, Nagpur - 440 018.Phone: 0712-2738731, 3296733; Telefax: 0712-2721216

Bengaluru : Plot No. 91-33, 2nd Main Road Seshadripuram, Behind Nataraja Theatre,Bengaluru-560020. Phone: 08041138821, 9379847017, 9379847005

Hyderabad : No. 3-4-184, Lingampally, Besides Raghavendra Swamy Matham, Kachiguda,Hyderabad - 500 027. Phone: 040-27560041, 27550139

Chennai : New-20, Old-59, Thirumalai Pillai Road, T. Nagar, Chennai - 600 017.Mobile: 9380460419

Pune : First Floor, "Laksha" Apartment, No. 527, Mehunpura, Shaniwarpeth(Near Prabhat Theatre), Pune - 411 030. Phone: 020-24496323/24496333;Mobile: 09370579333

Lucknow : House No. 731, Shekhupura Colony, Near B.D. Convent School, Aliganj,Lucknow - 226 022. Phone: 0522-4012353; Mobile: 09307501549

Ahmedabad : 114, “SHAIL”, 1st Floor, Opp. Madhu Sudan House, C.G. Road, Navrang Pura,Ahmedabad - 380 009. Phone: 079-26560126; Mobile: 09377088847

Ernakulam : 39/176 (New No.: 60/251) 1st Floor, Karikkamuri Road, Ernakulam,Kochi – 682011. Phone: 0484-2378012, 2378016 Mobile: 09387122121

Bhubaneswar : 5 Station Square, Bhubaneswar - 751 001 (Odisha).Phone: 0674-2532129, Mobile: 09338746007

Kolkata : 108/4, Beliaghata Main Road, Near ID Hospital, Opp. SBI Bank,Kolkata - 700 010, Phone: 033-32449649, Mobile: 7439040301

DTP by : Hansa Subhedar

Printed at : Rose Fine Art, Mumbai. On behalf of HPH.

Page 4: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

PrefaceNowadays Object oriented languages are playing a vital role in computing industry.

Object Oriented Programming (OOP) is an approach to program organization anddevelopment that attempts to eliminate some of the pitfalls of conventional programmingmethods by incorporating the best of structured programming features with severalpowerful new concepts. It is a new way of organizing and developing programs and hasnothing to do with any particular language.

This book uses C++ language to understand the concepts of object orientation.

This book explains the concepts such as classes, objects, inheritance, polymorphism,constructor, destructor, overloading, overriding, etc. in a simplest way.

This book also highlights access specifiers, file handling strings and streams,libraries in such a manner so that students can learn and explore their knowledge on thattopics.

It gives us immense pleasure to hand over this book and we trust that students willfind the book useful.

Authors

Page 5: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

SyllabusSubject: Object Oriented Programming with C++

Course Code: USIT304Class: B. Sc. (Information Technology) Semester – III

Unit Name of the Topic No. ofLectures

Unit – I Introduction to OOPs:Need of object oriented programming, comparison ofprocedural and object oriented approach, characteristics ofOOPs – object, classes, polymorphism, inheritance,reusability, data hiding and abstraction, applications ofOOPs.

8

Unit – II Classes and Objects:Class declaration, constructors, constructor initializationlists, access functions, private member functions, the copyconstructor, the class destructor, constant objects, structures,pointers to objects, static data members, static functionmembers.

8

Unit – III Operator Overloading:Overloading the assignment operator, the this pointer,overloading arithmetic operators, overloading the arithmeticassignment, operators, overloading the relational operators,overloading the stream operators, conversion operators,overloading the increment and decrement operators,overloading the subscript operator.

8

Unit – IV Composition and Inheritance:Inheritance, protected class members, overriding anddominating inherited members, private access versesprotected access, virtual functions and polymorphism,virtual destructors, abstract base classes.

8

Page 6: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

File Handling:Classes for file stream operations, opening and closing afile, detecting end of file, file modes, file pointers and theirmanipulations, sequential input and output operations,random access, file operations error handing, command lineargument.

Unit – V Strings and Streams:The string class interface, the constructors and destructor,the copy constructor, the assignment operator, the additionoperator, an append operator, access functions, thecomparison operators, stream operators.Stream classes, the ios class, ios format flags, ios state,variables, the istream and ostream classes, unformatted inputfunctions, unformatted output functions, streammanipulators.

8

Unit – VI Templates and Iterators:Function templates, class templates, container classes,subclass templates, passing template classes to templateparameters, iterator classes.Libraries:The standard C++ library, proprietary libraries, contents ofthe standard C headers, string streams, file processing, thestandard template library.

8

Page 7: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

Question Paper PatternMax. Marks: 75 Time: 2½ HrsInstructions:

1. All questions are compulsory.2. Attempt any TWO sub-questions from each question number 2-6 and any 3 from question

number 7.3. Each sub-question is of 5 marks.

Q.1 Answer the following: From unit 1 [10](a)(b)(c)(d)

Q.2 Answer the following: From unit 2 [10](a)(b)(c)(d)

Q.3 Answer the following: From unit 3 [10](a)(b)(c)(d)

Q.4 Answer the following: From unit 4 [10](a)(b)(c)(d)

Q.5 Answer the following: From unit 5 [10](a)(b)(c)(d)

Q.6 Answer the following: From unit 6 [10](a)(b)(c)(d)

Q.7 Answer any THREE of the following: [15](a) From unit 1(b) From unit 2(c) From unit 3(d) From unit 4(e) From unit 5(f) From unit 6

Page 8: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

Contents

Sr. No. Name Page No.

Unit - I: Introduction to OOPs

1. Introduction to OOPs 1 – 7

Unit - II: Classes and Objects2. Classes and Objects 8 – 14

3. Functions 15 – 20

4. Constructor and Destructor 21 – 26

Unit - III: Operator Overloading5. Operator Overloading 27 – 41

Unit - IV: Composition and Inheritance6. Composition and Inheritance 42 – 58

7. File Handling 59 – 68

Unit - V: Strings and Streams8. Strings 69 – 75

9. Streams 76 – 83

Unit - VI: Templates and Iterators10. Templates and Iterators 84 – 90

11. Libraries 91 – 102

List of Practicals 103 – 104

Model Question Paper 105 – 106

Page 9: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs
Page 10: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

CHAPTER

Introduction to OOPs1

Unit – I: Introduction to OOPs

Structure:1.1 Need of Object Oriented Programming1.2 Procedure Oriented Programming1.3 Object Oriented Programming1.4 Comparison of Procedural and Object Oriented Approach1.5 Characteristics of OOPs:

Object Classes Polymorphism Inheritance Reusability Data Hiding and Abstraction

1.6 Applications of OOPs

1.1 NEED OF OBJECT ORIENTED PROGRAMMING

Developments in software technology continue to be dynamic. New tools and techniques areannounced in quick succession. This has forced the software engineers and industry to continuouslylook for new approaches to software design and development, and they are becoming more and morecritical in view of the increasing complexity of software system as well as the highly competitivenature of the industry. This rapid advance appears to have created a situation of crises within theindustry. The following issues needs to be solved:

To represent real life entities of problems in system design. To design system with open interface. To ensure reusability and extensibility of modules. To develop modules that is tolerant to any changes in future.

Page 11: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

2 Object Oriented Programming with C++

To improve software productivity and decrease cost. To improve the quality of the software. To manage time schedule. To industrialize the software development process.

To overcome these problems and major motivation factor in the invention of object orientedapproach is to remove some of the flows encountered in the procedure oriented approach.

1.2 PROCEDURE ORIENTED PROGRAMMING

Conventional programming language using high level language such as Cobol and C, iscommonly known as Procedure Oriented Programming (POP). In Procedure Oriented Programming,the problem is viewed as a sequence of a thing to be done. A number of functions are written toaccomplish his task. The primary focus is on functions.

Procedure Oriented Programming basically consists of writing a list of instructions for thecomputer to follow, and organizing these functions into groups known as functions.

In a multi-function program, many important data items are placed as global so that they may beaccessed by all the functions. Each function may have its own local data.

Global data are more vulnerable to an inadvertent change by a function. In a large program it isvery difficult to identify what data is used by which function.

Another serious drawback with the procedural approach is that it does not model real worldproblems very well. This is because functions are action-oriented and do not really corresponding tothe elements of the problem.

Some characteristics of Procedure Oriented Programming are:1. Large programs are divided into smaller programs known as functions.2. Most of the functions share global data.3. Data move openly around the system from function to function.4. Functions transform data from one form to another.5. Employs top-down approach in program design.

1.3 OBJECT ORIENTED PROGRAMMING

Object Oriented Programming is the most recent concept among programming model. Themotivating factor in the invention of object oriented approach is to remove some of the flowsencountered in the procedural approach. OOPS treats data as a critical element in the programdevelopment and does not allow it to flow freely around the system. It binds data more closely to thefunctions that operate on it, and protects it from accidental modification from outside functions.

Some of the striking features of Object Oriented Programming are: Importance on data rather than procedure. Programs are divided into what are known as objects. Data structures are designed as such that they characterize the objects.

Page 12: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

Introduction to OOPs 3

Functions that operate on the data of an object are tied together in the data structure. Data is hidden and cannot be accessed by external functions. Objects may communicate with each other through functions. New data and functions can be easily added whenever necessary. Follow bottom-up approach in program design.

1.4 COMPARISON OF PROCEDURAL AND OBJECTORIENTED APPROACH

There are two different approaches to write a program, i.e., Procedure Oriented Programmingand Object Oriented Programming. Basic aim of these methods is nothing but to make programmingefficient. We can write the program using any of the way but there are notable differences betweenboth approaches.

Sr. No. Procedure Oriented Programming Object Oriented Programming1 POP is divided into small parts called as

functionsIn OOP, program is divided into parts calledobjects

2 In POP, Importance is not given to data butto functions as well as sequence of actions tobe done.

In OOP, Importance is given to the data ratherthan procedures or functions because it worksas a real world.

3 POP follows top-down approach. OOP follows bottom-up approach.4 POP does not have any access specifier. OOP has access specifiers named Public,

Private, Protected, etc.5 In POP, data can move freely from function

to function in the system.In OOP, objects can move and communicatewith each other through member functions.

6 To add new data and function in POP is notso easy.

OOP provides an easy way to add new dataand function.

7 In POP, most function uses global data forsharing that can be accessed freely fromfunction to function in the system.

In OOP, data cannot move easily fromfunction to function, it can be kept public orprivate so we can control the access of data.

8 POP does not have any proper way for hidingdata so it is less secure.

OOP provides data hiding so provides moresecurity.

9 In POP, overloading is not possible. In OOP, overloading is possible in the form ofFunction Overloading and OperatorOverloading.

10 Example of POP are: C, VB, FORTRAN,Pascal.

Example of OOP are: C++, JAVA, VB.NET,C#.NET.

1.5 CHARACTERISTICS OF OOPSCharacteristics of OOPs are: Object Classes

Page 13: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

4 Object Oriented Programming with C++

Polymorphism Inheritance Reusability Data abstraction and encapsulation

ObjectObjects are the basic run time entities in an Object Oriented System. They may represent a

person, a bank account, a table of data or any item that the program has to handle. They may alsorepresent user-defined data such as vector, time, and lists. When a program is executed, the objectsinteract by sending messages to one another. Creating objects is similar to declaring variables.

Syntax:

<Class Name> <Object Name>;

For Example:

Student s1;

Where Student is a class name and s1 is its object.

ClassesA class is an expanded concept of a data structure. Instead of holding only data, it can hold both

data and functions. On the other hand, we can say that object contains data and code to manipulate thatdata. Whereas the entire set of data and code of an object can be made with the help of class. Theobjects are the variables of type class.

Syntax:

class < Class Name > {data members…member functions…}

Here class is a keyword.

Rules for naming classes:

1. A class name must begin with a letter and can be followed by a sequence of letters (A-Z),digits (0-9) m, underscore (–).

2. Special Characters such as ? – + * / \ ! @ # $ % ^ ( ) [ ] { } , ; : . cannot be used in the classname.

3. A class name must not be the same as a reserved keyword such as using, public, etc.

Members of class can be divided into three different types i.e.:

(a) Private: Private members are accessible only in the class itself.

(b) Public: Public members are accessible outside the class (Anywhere)

(c) Protected: Protected members are accessible in the same package, and in the subclasses ofthe class and inside the class.

Page 14: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

Introduction to OOPs 5

PolymorphismPoly means many. Morphism means forms. Polymorphism feature enables classes to provide

different implementation of methods having the same name.

There are two types of polymorphism:1. Compile time (Overloading)2. Run time (Overriding)

InheritanceInheritance is the process by which objects of one class acquire the properties of objects of

another class. It supports the concept of hierarchical classification. The existing class is called as baseclass and a new class which is created on the basis of base class is called as derived class. There are 5different types of inheritance, i.e.:

Single level Multilevel Multiple Hierarchical Hybrid

ReusabilityThe concept of inheritance provides an important feature to the object-oriented language-

reusability. A programmer can take an existing class and, without modifying it, and additional featuresand capabilities to it. This is done by deriving a new class from an existing class.

Data Abstraction and Encapsulation The wrapping up of data and functions into a single unit is known as encapsulation. Data encapsulation is the most striking feature of a class. Abstraction refers to the act of representing essential features without including the

background details or explanations. Encapsulation is the hiding of information in order to ensure that data structures and

operators are used as intended and to make the usage model more obvious to the developer. C++ provides the ability to define classes and functions as its primary encapsulation

mechanisms.

1.6 APPLICATIONS OF OOPS

Object concept helps to translate our thoughts to a program. It provides a way of solving aproblem in the same way as a human being perceives a real world problem and finds out the solution.It is possible to construct large reusable components using object-oriented techniques. Development ofreusable components is rapidly growing in commercial software industries.

Page 15: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

6 Object Oriented Programming with C++

If there is complexity in software development, object-oriented programming is the bestparadigm to solve the problem. The following areas make the use of OOP:

1. Image Processing2. Pattern Recognition3. Computer Assisted Concurrent Engineering4. Computer Aided Design and Manufacturing5. Computer Aided Teaching6. Intelligent Systems7. Database Management Systems8. Web-based Applications9. Distributed Computing and Applications

10. Component-based Applications11. Business Process Re-engineering12. Enterprise Resource Planning13. Data security and management14. Mobile Computing15. Data Warehouse and Data Mining16. Parallel Computing

SUMMARY● Object oriented approach is used to remove some of the flows encountered in the procedure

oriented approach.● Procedure Oriented Programming basically consists of writing a list of instructions for the

computer to follow, and organizing these functions into groups known as functions. WhereasOOPs binds data more closely to the functions that operate on it, and protects it fromaccidental modification from outside functions. Characteristics of OOPs are object, classes,polymorphism, inheritance, reusability, data abstraction and data encapsulation.

● Objects are basic run time entities.● Class is an expanded concept of data structure.● Polymorphism feature enables classes to provide different implementation of methods

having the same name.● Inheritance is the process by which objects of one class acquire the properties of objects of

another class.● Reusability enables an existing class and, without modifying it, and additional features and

capabilities to it.● Abstraction refers to the act of representing essential features without including the

background details or explanations.● The wrapping up of data and functions into a single unit is known as encapsulation.

Page 16: Object Oriented - himpub.com · Unit – I Introduction to OOPs: Need of object oriented programming, comparison of procedural and object oriented approach, characteristics of OOPs

Introduction to OOPs 7

QUESTIONS1. Explain need of object oriented programming.2. Write short note on procedure oriented programming.3. Write short note on object oriented programming.4. Distinguish between procedure oriented programming and object oriented programming.5. Write characteristic features of procedure oriented programming.6. Write characteristic features of object oriented programming.7. Explain characteristics of OOPs in detail.8. Write applications of OOPs.