smple copy. not for distribution. - book editing · 2018. 5. 4. · viii chapter 7 details...

23
Smple Copy. Not For Distribution.

Upload: others

Post on 09-Mar-2021

8 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

Smple Copy. Not For Distribution.

Page 2: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

i

Object Oriented Programming with C++

Simplified

Smple Copy. Not For Distribution.

Page 3: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

ii

Publishing-in-support-of,

EDUCREATION PUBLISHING

RZ 94, Sector - 6, Dwarka, New Delhi - 110075 Shubham Vihar, Mangla, Bilaspur, Chhattisgarh - 495001

Website: www.educreation.in ____________________________________________________________________________

© Copyright, 2018, Dr. Anupama Chowdhary

All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted, in any form by any means, electronic, mechanical, magnetic, optical, chemical, manual, photocopying, recording or otherwise, without the prior written consent of its writer.

ISBN: 978-1-5457-1968-8

Price: ` 530.00

The opinions/ contents expressed in this book are solely of the author and do notrepresent the opinions/ standings/ thoughts of Educreation.

Printed in India

Smple Copy. Not For Distribution.

Page 4: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

iii

Object Oriented Programming with C++

Simplified

By

Dr. Anupama Chowdhary

EDUCREATION PUBLISHING (Since 2011)

www.educreation.in

Smple Copy. Not For Distribution.

Page 5: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

iv

Smple Copy. Not For Distribution.

Page 6: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

v

About the Author

Dr. Anupama Chowdhary has almost 20 years of teaching experience in the field of Computer Science and Information

Technology. Presently she is Principal of Keen College, Bikaner.

She has done her Bachelor of Science Honours degree in

Computer Science and Mathematics and Master of Science in

Computer Science from prestigious Banasthali Vidyapith in 1997. She completed her PhD in Computer Science and

Engineering. Her area of research is data mining, data

warehousing and cloud computing. She is author of four books.

She has published 10 research papers in international/ national level conferences /seminar / symposia/ workshops etc.

Under her guidance hundreds of students of MSc (Computer Science), MSc

(Information Technology), PGDCA, BCA and BBA stream developed their projects.

She is member of prestigious professional bodies like Computer Society of India, Board of Studies Maharaja Ganga Singh University, Bikaner.

She coordinated several training programmes for employees of State bank of India,

UCO bank, Bank of India, URMUL Dairy, Central Jail, and various state and private

organizations.

Smple Copy. Not For Distribution.

Page 7: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

vi

Acknowledgements

The task of publishing any book depends upon various important persons who inspire, support and encourage. Due to those persons the planning for publishing a

book executes.

I dedicate this small piece of work to my adored teacher, Late Dr. Rekha Govil mam.

Her devotion, work ethics and affectionate nature for students always inspired me to

be like her.

I would like to thank my daughter Nehal , son Utkarsh and specially, my husband

Kapil for their continues support and love throughout the writing of this book and

also within my own life.

Lastly, I would like to thank the staff and students of Keen College.

Smple Copy. Not For Distribution.

Page 8: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

vii

Preface

C++ is a general purpose programming language. The language has object-oriented, imperative and generic features. There are many other popular languages such as

C#, JAVA etc. but C++ is one of the widely used language for scripting. The large

segment of Android, Apple‘s OS X, various versions of Microsoft Windows, erstwhile

Symbian OS and UNIX operating system is scripted in this language. Many other

languages such as C#, JAVA, Limbo, JavaScript, Perl, PHP etc. are using this language in variable capacity.

The applications where higher degree of calculations are required like MATLAB,

Mathematica use this language. For scripting applications and drivers of embedded

systems this language is the first choice for programmers. A part of Google‘s back-end, rendering engine of web browser Mozilla Firefox and email client Mozilla

Thunderbird are coded in C++. Medical equipment‘s, such as MRI machines, use

C++ language for scripting their software. In engineering applications, such as high-

end CAD/CAM systems use this language.

This book is written for the people with no previous programming experience or

programmers who already know C and want to move on for C++. The book provides

plenty of examples and pictorial descriptions to explain the language concepts in a

simplified way. Exercises are designed to enhance language skills.

Chapter 1 introduces C++ language and its historical background. The basic

concepts of procedural and object oriented programming are elaborated here.

Chapter 2 explains the basic programming structure and gives you enough information to write a very simple program. This chapter provides detailed

description of directives, comments, variables, constants, data types – basic and

derived, typedef, operators, expressions and type conversion.

Control structures are explained in chapter 3. Decision statements if-else, switch, conditional operator, goto and loop statements for, while and do-while are covered

here. Moreover the significance of break and continue are elaborated.

Chapter 4 covers array one dimensional and multidimensional, character array, arrays and structures, pointers, dynamic memory allocation and pointers with arrays

and structures.

User defined functions are described in chapter 5 including call by value, call by

reference, return by reference, inline functions, default and constant arguments, array and struct with functions, pointer to functions, nesting of function, recursion

and storage classes.

The chapter 6 provides basic object oriented concept – class. This chapter explains how to define and use a class, objects, data and function members, pointer ‗this‘,

constant and static data and function members, pointers to members, local classes

and namespaces.

Smple Copy. Not For Distribution.

Page 9: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

viii

Chapter 7 details constructor – default, parameterized and copy constructor,

overloading constructors, initializer list, default arguments to constructors, dynamic initialization of objects, dynamic constructors, constant objects and destructors.

Chapter 8 covers inheritance – single, multiple, multilevel, hierarchical and hybrid.

Behaviour of constructors and destructors in inherited and base classes is described here. Moreover virtual base classes and nesting of classes (aggregation) is also

covered.

The concepts of friend and virtual functions are covered in chapter 9. Pointers to derived classes, early and late binding and abstract classes are covered here.

Chapter 10 describes operator overloading. The major topics covered here are

overloading unary, arithmetic, << and >>, relational, logical and assignment operators, manipulation of strings, restrictions on overloading operators and type

conversions.

Chapter 11 describes to define and use function and class templates. Major

concepts of standard template library (STL) such as container, algorithm and iterators are detailed here.

Chapter 12 is about exception handling. It details the mechanism of handling

exceptions, re-throwing exceptions, specified exceptions, standard exceptions and advantages of using exceptions.

Stream class is covered in chapter 13. It elaborates hierarchy of stream classes, ios

class, ostream class, istream class, withassign classes, formatted and unformatted I/O, file handling and command line arguments.

Smple Copy. Not For Distribution.

Page 10: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

ix

Content List

Sr. No. Content Page

1. Introduction to C++ 1

1.1 Introduction 1

1.2 Programming 2

1.3 Object-Oriented Programming 4

1.3.1 Object 5

1.3.2 Class 5

1.3.3 Encapsulation 6

1.3.4 Abstraction 7

1.3.5 Inheritance 7

1.3.6 Polymorphism 7

1.3.7 Reusability 8

1.3.8 Dynamic Binding 8

1.3.9 Message Passing 8

Exercises 9

2. Declarations and Data Types 10

2.1 Program structure 10

2.2 Directives 11

2.2.1 Pre-processor directives 11

2.2.1.1 #define 11

2.2.1.2 #undef 13

2.2.1.3 #ifdef, #ifndef, #if, #endif, #else and #elif 13

2.2.1.4 #line (Line control) 14

2.2.1.5 #error 15

2.2.1.6 #include 15

2.2.1.7 #pragma 16

2.2.2 Using directives 16

2.3 Comments 16

2.4 Variables and constants 17

2.5 Data types 18

2.5.1 Boolean (bool) 18

Smple Copy. Not For Distribution.

Page 11: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

x

2.5.2 Character (char) 19

2.5.3 Integer (int) 21

2.5.4 Floating-Point (float, double) 22

2.5.5 Void (void) 23

2.5.6 Enumerations (enum) 23

2.5.7 Structures (struct) 25

2.5.8 Unions (union) 28

2.5.9 Class and objects 30

2.5.10 typedef 31

2.6 Operators 32

2.6.1 Unary 32

2.6.2 Binary 34

2.6.3 Ternary 38

2.6.4 Additional operators in C++ 38

2.6.5 Expressions, Precedence and Associativity 42

2.6.6 Implicit conversions 43

2.6.7 Operator overloading 43

Exercises 44

3. Control Structures 46

3.1 Introduction 46

3.2 Decision Statements 46

3.2.1 if-else Statement 46

3.2.2 switch Statement 51

3.2.3 Conditional Operator 54

3.2.4 goto Statement 54

3.3 Loop Statements 54

3.3.1 for Loop 55

3.3.2 while Loop 57

3.3.3 do-while Loop 61

3.4 break Statement 62

3.5 continue Statement 64

Exercises 65

4. Arrays and Pointers 68

4.1 Introduction to Arrays 68

4.1.1 One Dimensional Array 68

4.1.2 Multi-dimensional array 71

4.2 Character Array 76

4.3 Arrays and Structures 84

Smple Copy. Not For Distribution.

Page 12: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

xi

4.4 Pointer 86

4.4.1 Pointers and addresses 87

4.4.2 Address Arithmetic 91

4.5 Pointers and Arrays 92

4.6 Dynamic Memory Allocation 95

4.7 Pointer Arrays 98

4.8 Pointer and Structure 100

Exercises 101

5. Functions 103

5.1 Introduction 103

5.2 Call by value 106

5.3 Call by Reference 107

5.4 Return by Reference 109

5.5 Inline Functions 109

5.6 Default Arguments in Functions 111

5.7 Constant Arguments in Functions 112

5.8 Function and Array 112

5.9 Function and Structure 116

5.10 Pointer to Function 118

5.11 Function Overloading 120

5.12 Nesting of Functions 121

5.13 Recursion 122

5.14 Storage Classes 124

5.14.1 Global and External Variable 125

5.14.2 Local/Automatic Variable 128

5.14.3 Register Variable 129

5.14.4 Static Variable 129

Exercises 130

6. Classes 132

6.1 Introduction 132

6.2 Defining and using the Class 134

6.2.1 Defining objects 135

6.3 Memory layout 138

6.4 Characteristics of Member functions 138

6.5 Arrays and class 140

6.6 Objects as function arguments 143

6.7 Returning Objects from functions 146

6.8 Pointer ‗this‘ 147

Smple Copy. Not For Distribution.

Page 13: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

xii

6.9 Constant member functions 149

6.10 Static Data Member 150

6.11 Static Member Functions 151

6.12 Pointers to members 153

6.13 Local Classes 155

6.14 Namespaces 156

Exercises 158

7. Constructors and Destructors 160

7.1 Constructor 160

7.2 Default Constructor 161

7.3 Parameterized Constructor 161

7.4 Copy Constructor 162

7.5 Overloading/Multiple Constructors 165

7.6 Initializer List 166

7.7 Default Arguments 177

7.8 Dynamic initialization of objects 168

7.9 Dynamic constructors 168

7.10 Constant Objects 171

7.11 Destructors 172

Exercises 174

8. Inheritance 175

8.1 Introduction 175

8.2 Single Inheritance 177

8.3 Multilevel Inheritance 182

8.4 Multiple Inheritance 184

8.5 Hierarchical Inheritance 188

8.6 Hybrid Inheritance 189

8.7 Virtual Base Classes 191

8.8 Constructors/Destructor and Inheritance 193

8.9 Nesting of Classes (Aggregation) 199

Exercises 201

9. Friend and Virtual Functions 203

9.1 Friend Function 203

9.2 Pointers to Derived Classes 206

9.3 Virtual Functions 208

9.3.1 Early and Late Binding 210

9.3.2 Pure Virtual Functions and Abstract Classes 211

Exercises 212

Smple Copy. Not For Distribution.

Page 14: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

xiii

10. Operator Overloading 213

10.1 Introduction 213

10.2 The operator Keyword 215

10.3 Overloading Unary Operators 216

10.4 Overloading Binary Operators 220

10.5 Overloading Arithmetic Operators 220

10.6 Overloading >> and << Operators 222

10.7 Overloading Relational Operators 224

10.8 Overloading Logical Operators 226

10.9 Overloading Assignment Operators 227

10.10 Manipulation of Strings 228

10.11 Restrictions on Overloading the Operators 230

10.12 Type Conversion 231

10.12.1 Conversions Between Basic Types 232

10.12.2 Conversions from Basic Type to Class Type 233

10.12.3 Conversions from Class Type to Basic Type 234

10.12.4 Conversions from one Class Type to another Class Type

235

Exercises 237

11. Templates 239

11.1 Introduction 239

11.2 Function Templates 239

11.3 Overloading Function Templates 243

11.4 Class Templates 243

11.5 Standard Template Library (STL) 246

11.5.1 Container 246

11.5.2 Algorithms 248

11.5.3 Iterators 252

Exercises 253

12. Exceptions 255

12.1 Introduction 255

12.2 Mechanism of Exception handling 255

12.3 Re-throwing an exception 261

12.4 Specified Exceptions 262

12.5 Standard Exceptions 263

12.6 Advantages of exception handling 264

Exercises 264

Smple Copy. Not For Distribution.

Page 15: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

xiv

13. Stream Classes 266

13.1 Introduction 266

13.2 Hierarchy of Stream Class 267

13.3 The ios Class 267

13.3.1 The formatting flags 268

13.3.2 Manipulators 268

13.3.3 Functions 269

13.4 The ostream Class 270

13.5 The istream Class 270

13.6 The iostream and the _withassign Classes 271

13.7 Formatted and Unformatted I/O Operations 272

13.8 File Handling 274

13.8.1 Opening/Creating a File 274

13.8.2 Reading and Writing Data 276

13.8.3 Closing a File 278

13.8.4 File Pointers 278

13.8.5 State Flags and End-of-File Detection 279

13.9 Command Line Arguments 284

Exercises 286

Appendix A ASCII character Set 287

Appendix B Keywords 295

Smple Copy. Not For Distribution.

Page 16: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

Object Oriented Programming with C++

1

Chapter 1

Introduction to C++

_____________________________________________________________________________________

1.1 Introduction

Dennis Ritchie of Bell Laboratories was engaged in a project to develop a new

operating system in the early 1970s. He discovered that in order to accomplish his

task he needed the use of a programming language that was concise and that

produced compact and speedy programs. This need led Ritchie to develop the programming language called C.

At Bell Laboratories, another programming language was created which was based

upon the C language in the early 1980's. This new language was developed

by Bjarne Stroustrup, called C++. He added OOP (Object Oriented Programming) features to C without significantly changing the C component. Thus C++ is a

"relative" (called a superset) of C, meaning that any valid C program is also a valid

C++ program. But the similarity is largely a historical accident. In fact, the basic

approach in a C++ program is very different from that in a C program.

C++ have very close correspondence between its types, operators, and statements and the objects that computers deal with directly: numbers, characters, and

addresses. Except for the new, delete, typeid, dynamic_cast, and throw operators

and the try-block, individual C++ expressions and statements need no run-time

support.

A C++ program declaring function argument types, using classes, etc., is normally a

bit shorter than the equivalent C program. Where libraries are used, a C++ program

will appear much shorter than its C equivalent.

It is not necessary or advantageous to teach C before teaching C++. Students who already know C may be able to browse parts of some chapters, but they will find that

a notable percentage of the concepts are new.

There are several versions of the C++ language, of which Visual C++ is only one.

Other dialects include Borland C++, Turbo C++, and Code Warrior (Mac). All of these software packages enable you to create computer programs with C++, but

they all implement the C++ language in a slightly different manner. In an attempt to

maintain portability of both the C and C++ languages, the American National

Standards Institute (ANSI) developed a standard of consistency for C and C++

programming. Due to their power and ease of use, C and C++ were used in the programming of the special effects for Star Wars.

If you are a C programmer it will be difficult for you to avoid writing C++ in C style,

thereby losing some of the potential benefits of C++. In some of the following areas

C++ has better ways of doing something than C has:

In place of macros or symbolic constants use const or enum to define constants.

inline to avoid function-calling overhead, templates to specify families of

functions and types, and namespaces to avoid name clashes.

Smple Copy. Not For Distribution.

Page 17: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

Dr. Anupama Chowdhary

2

A declaration can occur anywhere as a statement can, so don‘t declare a variable

before you need it so that you can initialize it immediately.

Don‘t use malloc() use new operator, as it does the same job better. Instead of realloc(), try a vector.

Try to avoid void*, pointer arithmetic, unions, and casts. In most cases, a cast is

an indication of a design error. If in some situations you have to use an explicit

type conversion, try using one of the ‗‗new casts‘‘ such as static_cast or reinterpret_cast.

Minimize the use of arrays and C-style strings, use C++ standard library string

and vector classes to simplify programming compared to traditional C style.

In general, try not to build yourself what has already been provided by the standard library.

Most important, try thinking of a program as a set of interacting concepts

represented as classes and objects, instead of as a bunch of data structures with

functions handling their bits.

1.2 Programming

The approach for designing a program has three stages.

Analysis: gain a clear understanding of the problem.

Design: identify the key concepts involved in a solution. Programming: express that solution in a program.

The details of the problem and the concepts of the solution become clearly

understood after we try to express them in a program and trying to get it to run

acceptably.

While expressing solution in a C++ program declare a class to represent key

concepts involved in a solution (design). C++ class specifies how objects of its class

will behave: how objects are represented, how they are created, how they can be

manipulated and how they are destroyed. So the basic points you have to keep in

mind are:

How to create objects of this class?

Shall we provide facility to copy objects of this class?

Shall we provide facility to destroy objects of this class? What operational facility should be provided to objects of this class?

If there are no good answers to such questions, probably you do not gain a clear

understanding of the problem. It might then be a good idea to think more about the problem and its proposed solution instead of immediately starting to code the

problems.

Numbers of all sorts, sets, geometric shapes, etc. Text-oriented I/O, strings, basic

containers, the fundamental algorithms on such containers, and some mathematical

classes are part of the standard C++ library. These concepts are easiest to deal with.

It is easy to design the individual classes, but a concept does not exist in a void;

there are always clusters of related concepts. Organizing the relationship between

classes in a program – that is, determining the exact relationship between the

different concepts involved in a solution is often harder. Situations in which every class (concept) depends on every other, the result had better not be a tangle. For

example if there are two classes, X and Y. Relationships such as ‗‗X calls functions

from Y,‘‘ and ‗‗X has a Y member‘‘ rarely cause major problems, while relationships

such as ‗‗X uses data from Y‘‘ can be eliminated.

Hierarchical ordering is one of the most powerful intellectual tools for managing

complexity. It organizes related concepts into a tree structure with the most general

Smple Copy. Not For Distribution.

Page 18: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

Object Oriented Programming with C++

3

concept as the root. In C++, derived classes represent such structures. A program

can often be organized as a set of trees or directed acyclic graphs of classes. That is,

the programmer specifies a number of base classes, each with its own set of derived classes. Virtual functions can often be used to define operations for the most general

version of a concept (a base class). When necessary, the interpretation of these

operations can be refined for particular special cases (derived classes).

Sometimes even a directed acyclic graph seems insufficient for organizing the concepts of a program; some concepts seem to be inherently mutually dependent. In

that case, we try to localize cyclic dependencies so that they do not affect the overall

structure of the program. If you cannot eliminate or localize such mutual

dependencies, then you are most likely in a difficulty that no programming language can help you out of. Unless you can conceive of some easily stated relationships

between the basic concepts, the program is likely to become unmanageable.

C++ uses Abstract classes for clean separation of interface and implementation. A

class template specifies a family of classes for expressing commonality i.e. Template is a mechanism for specifying how one type is generated given another type as an

argument. The most common templates are container classes such as lists, vectors,

and associative arrays (maps) and the fundamental algorithms using such

containers. It is usually a mistake to express parameterization of a class and its

associated functions with a type using inheritance; it is best done using templates.

Do’s

While coding, you create an actual representation of your ideas in your solution to

some problem. The structure of the program should reflect those ideas as directly as possible:

1) If you can think of it as a separate idea, make it a class.

2) If you can think of it as a separate entity, make it an object of some class.

3) If two classes have a common interface, make that interface an abstract class. 4) If the implementations of two classes have something significant in common,

make that commonality a base class.

5) If a class is a container of objects, make it a template.

6) If a function implements an algorithm for a container, make it a template

function implementing the algorithm for a family of containers. 7) If a set of classes, templates, etc., are logically related, place them in a common

namespace.

Don’ts

When you define either a class that does not implement either a mathematical entity

like a matrix or a complex number or a low-level type such as a linked list:

1) Don‘t use global data (use members).

2) Don‘t use global functions. 3) Don‘t use public data members.

4) Don‘t use friends, except to avoid 1 or 3.

5) Don‘t put a ‗‗type field‘‘ in a class; use virtual functions.

6) Don‘t use inline functions, except as a significant optimization.

1.3 Object-Oriented Programming

Object oriented programming is based upon the objects. In real world for instance

objects are like car, scooty, microwave oven, bicycle and many more. Each of these

objects has their parts and some procedure to operate these parts. Accelerator and brake procedures of car are used to operate its parts. The important point is that

Smple Copy. Not For Distribution.

Page 19: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

Dr. Anupama Chowdhary

4

only the internal accelerator and break procedure can be used to operate on internal

parts of that car.

In OOPs programming, data is treated as crucial elements and should not be exposed to the procedures outside the object. In procedural programming the data

could be accessed by everyone. The major difference between procedural and OOPs

programming is provisions for accessing data (table 1.1).

Table 1.1

Comparison of Procedural programming and Object Oriented

Programming

Procedural programming Object Oriented Programming

Importance is on algorithms Importance is on data

Large programmes are divided into functions

Programmes are divided into objects

Functions share global data Data structures are used and they provide public data and functions.

Data move openly from function to

function

Data is hidden. Objects can move

and communicate with each other through member functions

Top down approach is used Bottom up approach is used

No access specifiers are used Public, Private, Protected, etc.

specifiers are used

Difficult to add new data and

functions

Easy to add new data and functions

Less secure: there are no

provisions for data hiding

More secure: Data is hidden

Overloading is not possible Function and operator overloading

is possible

C, Pascal, FORTRAN et. Are

procedural languages

C++, JAVA, C#.NET VB.NET etc.

are OOPs languages

There are a few principle concepts that form the foundation of object-oriented

programming to simplify the software development and maintenance.

Object

Class

Encapsulation

Abstraction Inheritance

Polymorphism

Reusability

Dynamic binding Message passing

1.1.1 Object

This is the basic unit of object oriented programming. That is both data and function

that operate on data are encapsulated as a unit called as object. In OOPs the

programmer will not think to divide the problem into functions rather he thinks to

Smple Copy. Not For Distribution.

Page 20: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

Object Oriented Programming with C++

5

divide the problem into objects. So the programmers have to match the real world

objects with the objects in the programming sense.

How will you decide that this kind of thing could become objects in object-oriented

programs? However, this depends upon your imaginations.

Example 1:

Objects of the computer-user environment:

Windows

Mouse

Keyboard Disk drives

Printer

Menus

Graphics objects (lines, rectangles, circles)

Example 2:

Objects in computer games

Cars in an auto race

Positions in a board game (chess, checkers) Opponents and friends in adventure games

Objects are basic run-time entities in an object oriented system, objects are

instances of a class.

1.1.2 Class

Class is a blueprint of data and functions or methods. It specifies what data and what

functions will be included in objects of that class. Defining the class doesn‘t create any objects. It is a logical entity. Class does not take any space. Class declaration is

similar to struct declaration keyword ‗class‘ followed by class name. There are two

types of members in a class

Data members / attributes

Member functions / methods

Data members of a class can be any of primary data types (int, float, char, double,

bool) or secondary data types (arrays, pointers, class objects etc.). Data members

are classified into two groups

Regular: every object gets its own copy of data members

Static: all objects share the same copy of data member

The function defined inside a class declaration is called as member function or method. Methods can be defined inside the class or outside the class using scope

resolution operator (::). When the functions are defined outside class declaration,

function needs to be declared inside the class. Member functions in a class could be

regular functions, overloaded functions, inline functions, friend functions, static functions, constructors, destructors, and virtual functions.

class sample

{

private:

int x;

Smple Copy. Not For Distribution.

Page 21: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

Dr. Anupama Chowdhary

6

public:

sample(): x(2){}

~sample();

void getx();

void showx();

};

Table 1.2

Comparison of class and object

Class Object

Class is mechanism of binding data members and associated methods in a

single unit.

Instance of class or variable of class.

It‘s existence is logical It‘s existence is physical

Memory space is not allocated , when it is created

Memory space is allocated, when it is created

Definition is created once It is created many time as you

require

It is a concept It is a phenomenon

A class is a part of a program An object is part of data and a

program execution

A description of the common

properties of a set of objects.

A representation of the properties

of a single

instance

1.1.3 Encapsulation

Encapsulation is the process of wrapping up of data and behaviour of an object into a

single unit; and the unit here is a class. Encapsulate in plain English means to

enclose or as if in a capsule. To achieve encapsulation, we make all data members of

class private and create public functions or methods; using them we can get the values from these data members or set the value to these data members.

Encapsulation enables data hiding, hiding irrelevant information from the users of a

class and exposing only the relevant details required by the user.

We can expose our operations, hiding the details of what is needed to perform

that operation. We can protect the internal state of an object by hiding its attributes from the

outside world by making it private, and then exposing them through methods.

Now the modifications to the object internals are only controlled through these

methods.

1.1.4 Abstraction

Abstraction is a process of hiding irrelevant details from user. For example, When

you send an email you just type the message, select the contact and click send, the

system shows you that the message has been sent, what actually happens in

background when you click send is hidden from you as it is not relevant to you.

Smple Copy. Not For Distribution.

Page 22: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

Get Complete Book

At Educreation Store

www.educreation.in

Smple Copy. Not For Distribution.

Page 23: Smple Copy. Not For Distribution. - Book Editing · 2018. 5. 4. · viii Chapter 7 details constructor – default, parameterized and copy constructor, overloading constructors, initializer

Smple Copy. Not For Distribution.