Important Announcement
PubHTML5 Scheduled Server Maintenance on (GMT) Sunday, June 26th, 2:00 am - 8:00 am.
PubHTML5 site will be inoperative during the times indicated!

Home Explore BCA122_OOPS(Draft 2)(1)

BCA122_OOPS(Draft 2)(1)

Published by Teamlease Edtech Ltd (Amita Chitroda), 2020-12-20 16:38:42

Description: BCA122_OOPS(Draft 2)(1)

Search

Read the Text Version

BACHELOR OF COMPUTER APPLICATIONS SEMESTER-II OBJECT ORIENTED PROGRAMMING BCA122 1 CU IDOL SELF LEARNING MATERIAL (SLM)

CHANDIGARH UNIVERSITY Institute of Distance and Online Learning Course Development Committee Chairman Prof. (Dr.) Parag Diwan Vice Chancellor, Chandigarh University, Gharuan, Punjab Advisors Prof. (Dr.) Bharat Bhushan, Director – IGNOU Prof. (Dr.) Majulika Srivastava, Director – CIQA, IGNOU Programme Coordinators & Editing Team Master of Business Administration (MBA) Bachelor of Business Administration (BBA) Coordinator – Dr. Rupali Arora Coordinator – Dr. Simran Jewandah Master of Computer Applications (MCA) Bachelor of Computer Applications (BCA) Coordinator – Dr. Raju Kumar Coordinator – Dr. Manisha Malhotra Master of Commerce (M.Com.) Bachelor of Commerce (B.Com.) Coordinator Coordinator – Dr. Aman Jindal – Dr. Minakshi Garg Master of Arts (Psychology) Bachelor of Science (Travel &Tourism Management) Coordinator – Dr. Samerjeet Kaur Co-ordinator – Dr. Shikha Sharma Master of Arts (English) Coordinator Bachelor of Arts (General) – Dr. Ashita Chadha Co-ordinator – Ms. Neeraj Gohlan Academic and Administrative Management Prof. (Dr.) R. M. Bhagat Prof. (Dr.) S.S. Sehgal Executive Director – Sciences Registrar Prof. (Dr.) Abhishek Prof. (Dr.) Inderpreet Kaur Executive Director – Management Director – IDOL Prof. (Dr.) Manaswini Acharya Executive Director – Liberal Arts © No part of this publication should be reproduced, stored in a retrieval system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording and/or otherwise without the prior written permission of the authors and thepublisher. SLM SPECIALLY PREPARED FOR CU IDOL STUDENTS Printed and Published by: SCHOOLGURU EDUSERVE PVT LTD B-903, Western Edge II, Western Express Highway, Borivali (E), Mumbai - 400066 Call Us: +91 22 4896 8005 Mail Us: [email protected] For: CHANDIGARH UNIVERSITY Institute of Distance and Online Learning 2 CU IDOL SELF LEARNING MATERIAL (SLM)

First Published in 2020 All rights reserved. No Part of this book may be reproduced or transmitted, in any form or by any means, without permission in writing from Chandigarh University. Any person who does any unauthorized act in relation to this book may be liable to criminal prosecution and civil claims for damages. This book is meant for educational and learning purpose. The authors of the book has/have taken all reasonable care to ensure that the contents of the book do not violate any existing copyright or other intellectual property rights of any person in any manner whatsoever. In the even the Authors has/ have been unable to track any source and if any copyright has been inadvertently infringed, please notify the publisher in writing for corrective action. 3 CU IDOL SELF LEARNING MATERIAL (SLM)

CONTENT Unit 1: Fundamentals of C++ 1 ......................................................................................... 4 Unit 2: Fundamentals of C++ 2 ....................................................................................... 20 Unit 3 : Classes and Objects 1 ......................................................................................... 42 Unit 4 : Classes and Objects 2 ......................................................................................... 75 Unit 5:Constructors and Destructors.............................................................................. 98 Unit6:Inheritance........................................................................................................... 119 Unit 7 :Polymorphism.................................................................................................... 156 Unit8:Exception Handling............................................................................................. 187 Unit 9:Pointer & Virtual Function................................................................................ 203 Unit 10: Dynamic memory allocation ........................................................................... 225 Unit 11: Files .................................................................................................................. 238 4 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 1FUNDAMENTALS OF C++ 1 Structure 1.0 LearningObjectives 1.1 Introduction 1.2 Featured of object-oriented programming 1.3 Difference between object oriented and procedure oriented programming 1.4 Difference between structure and classes 1.5 Summary 1.6 KeyWords/Abbreviations 1.7 LearningActivity 1.8 Unit End Questions (MCQ andDescriptive) 1.9 References 1.0LEARNINGOBJECTIVES After studying this unit, you will be able to:  Explain the basic concepts of object-oriented programming.  Discuss Difference between object oriented and procedure oriented programming.  State Difference between structure and classes. 1.1INTRODUCTION Featured of object- Object-oriented programming (OOP) is a computer programming model that organizes software design around data, or objects, rather than functions and logic. An object can be defined as a data field that has unique attributes and behavior.OOP focuses on 5 CU IDOL SELF LEARNING MATERIAL (SLM)

the objects that developers want to manipulate rather than the logic required to manipulate them. This approach to programming is well-suited for programs that are large, complex and actively updated or maintained. Object-Oriented Programming (OOP) is the term used to describe a programming approach based on objects and classes. The object-oriented paradigm allows us to organize software as a collection of objects that consist of both data and behavior. This is in contrast to conventional functional programming practice that only loosely connects data and behaviour.Since the 1980s the word 'object' has appeared in relation to programming languages, with almost all languages developed since 1990 having object-oriented features. Some languages have even had object-oriented features retro-fitted. It is widely accepted that object-oriented programming is the most important and powerful way of creating software. 1.2 FEATURED OF OBJECT ORIENTED PROGRAMMING The prime purpose of C++ programming was to add object orientation to the C programming language, which is in it one of the most powerful programming languages. The core of the pure object-oriented programming is to create an object, in code, that has certain properties and methods. While designing C++ modules, we try to see whole world in the form of objects. For example a car is an object which has certain properties such as color, number of doors, and the like. It also has certain methods such as accelerate, brake, and so on. Procedural programming deals with functional parts of the problem. Programmers identify what actions must be taken to solve the problem at hand. Let us now, try to understand what aspect of problems is dealt with in object-oriented approach. We shall be discussing some essential concepts that make a programming approach object-oriented. In object-oriented parlance, a problem is viewed in terms of the following concepts: 1. Objects 2. Classes 3. Data abstraction 4. Data encapsulation 6 CU IDOL SELF LEARNING MATERIAL (SLM)

5. Inheritance 6. Polymorphism 7. Dynamic binding 8. Message passing Object oriented programming-is not the right of any particular language. Although languages like C and Pascal can be used but programming becomes clumsy and may generate confusion when program grow in size. A language that is specially designed to support the OOP concepts makes it easier to implement them. To claim that they are object- oriented they should support several concepts of OOP. Depending upon the features they support, they are classified into the following categories: 1. Object-based programming languages 2. Object-oriented programming languages. Table 1.1 characteristics of object oriented programming 7 CU IDOL SELF LEARNING MATERIAL (SLM)

Major features required by object-based programming are: 1. Data encapsulation. 2. Data hiding and access mechanisms. 3. Automatic initialization and clear-up of objects. 4. Operator overloading. Languages that support programming with objects are said to be object-based programming languages. These do not support inheritance and dynamic binding ADA is a typical example Object oriented programming incorporates all of objects-based programming features along with two additional features, namely, inheritance and dynamic binding. Thus Object oriented programming = Object-based features + inheritance + dynamic binding. 1.3 DIFFERENCE BETWEEN OBJECT ORIENTED ANDPROCEDURE 8 CU IDOL SELF LEARNING MATERIAL (SLM)

ORIENTED PROGRAMMING Computer programming has been around for some decades now. The style and manner in which people have been developing programs itself has undergone a sea change. In the early days of computer development programming was looked upon as some kind of black magic – to be understood only by a few wizards mostly the people who had designed the computer. However, the entire scenario has changed now. In the modern programming parlance, at least in most of the commercial and business applications areas, programming has been made independent of the target machine. This machine independent characteristic of programming has given rise to a number of different methodologies in which programs can now be developed. We will particularly concern ourselves with two broad programming approaches – or paradigm as they are called in the present context. 1. Object-oriented paradigm 2. Procedure-oriented paradigm Object-oriented Programming Paradigm -The term Object-oriented Programming (OOP) is widely used, but experts do not seem to agree on its exact definition. However, most experts agree that OOP involves defining Abstract Data Types (ADT) representing complex real-world or abstract objects and organizing programs around the collection of ADTs with an eye toward exploiting their common features. The term data abstraction refers to the process of defining ADTs; inheritance and polymorphism refer to the mechanisms that enable you to take advantage of the common characteristics of the ADTs – the objects in OOP. Before going any further into OOP, take note of two points. First, OOP is only a method of designing and implementing software. Use of object-oriented techniques does not impart anything to a finished software product that the user can see. However, as a programmer while implementing the software, you can gain significant advantages by using object-oriented methods, especially in large software projects. Because OOP enables you to remain close to the conceptual, higher-level model of the real world problem you are trying to solve, you can manage the complexity better than with approaches that force you to map the problem to fit the features of the language. You can take advantage of the modularity of objects and implement the 9 CU IDOL SELF LEARNING MATERIAL (SLM)

Benefits of OOPS- Object-orientation contribute to the solution of many problems associated with the development and quality of software products. The technology provides greater programmer productivity, better quality of software and lesser maintenance cost. The principle advantages are: 1. Through inheritance, we can eliminate redundant code and extend the use of existing classes. 2. We can build programs from the standard working modules that communicate with one another, rather than having to start writing the code from scratch. This leads to saving of development time and higher productivity. 3. The principle of data hiding help the programmer to build secure programs that cannot be invaded by code in other parts of the program. 4. It is possible to have multiple instances of an object to co-exist without any interference. 5. It is possible to map objects in the problem domain to those objects in the program. 6. It is easy partition the work in a project based on objects. 7. The data-centered design approach enables us to capture more details of a model in implementable form. 8. Object oriented systems can be easily upgraded from small to large systems. 9. Message passing techniques for communication between objects makes the interface descriptions with external systems much simpler. 10. Software complexity can be easily managed. Applications of OOP-  Object-oriented approach offers perhaps the most logical description of the real world. Therefore, it can be applied in almost all the situations of problem solving. Because of its effectiveness in problem solving and programming, OOP has been adopted all over the software industry.  The existing systems are being migrated to OOP. One important aspect of OOP that 10 CU IDOL SELF LEARNING MATERIAL (SLM)

is particularly beneficial is the framework, which encompasses all the phases of a system development. Thus, OOA (Object Oriented Analysis), OOD (Object Oriented Design), OOT (Object Oriented Testing) etc. are far more suitable tools than their non-object-oriented counterparts. Above all, the reusability feature of the Object Oriented approach has facilitated the rapid growth of software both in variety and scope. Procedure-oriented Programming -Paradigm Before you get into OOP, take a look at conventional procedure-oriented programming in a language such as C. Using the procedure-oriented approach; you view a problem as a sequence of things to do such as reading, calculating and printing. Conventional programming using high-level languages is commonly known as procedure-oriented programming.Example: COBOL, FORTRAN and C You organize the related data items into C structures and write the necessary functions (procedures) to manipulate the data and, in the process, complete the sequence of tasks that solve your problem. Fig 1.1 Typical Structure of Procedure-oriented Programs A typical program structure for procedural programming is shown in Figure 1.1. The technique of hierarchical decomposition has been used to specify the tasks to be completed in order to solve a problem. Procedure oriented programming basically consists of writing a 11 CU IDOL SELF LEARNING MATERIAL (SLM)

list of instructions for the computer to following and organizing these instructions into groups known as functions. We normally use a flowchart to organize these actions and represent the flow of control from one action to another. While we concentrate on the development of functions, very little attention is given to the data that are being used by various functions. What happens to the data? How are they affected by the functions that work on them? In a multi-function program, many important data items are placed as global so that they may be accessed by all the functions. Each function may have its own local data. Figure 1.2 shows the relationship of data and functions in a procedure-oriented program. Global data are more vulnerable to an inadvertent change by a function. In a large program it is very difficult to identify what data is used by which function. In case we need to revise an external data structure, we should also revise all functions that access the data. This provides an opportunity for bugs to creep in. Fig 1.2 Relationships of Data and Functions in Procedural Programming The basic feature of Procedural-oriented Programming is to reuse the same code at different places in the program without coping it. Another serious drawback with the procedural approach is that it does not model real world problems very well. This is because functions are action-oriented and do not really corresponding to the elements of the problem. Some characteristics exhibited by procedure-oriented programming are: 1. Emphasis is on doing things (algorithms). 2. Large programs are divided into smaller programs known as functions. 12 CU IDOL SELF LEARNING MATERIAL (SLM)

3. Most of the functions share global data. 4. Data move openly around the system from function to function. Table 1.2 Procedural oriented programming VS Object oriented programming Procedural oriented programming Object oriented programming In procedural programming, program is In object oriented programming, program divided into small parts called functions. is divided into small parts called objects. Procedural programming follows top down Object oriented programming approach. follows bottom up approach. There is no access specifier in procedural Object oriented programming have access programming. specifiers like private, public, protected etc. Adding new data and function is not easy. Adding new data and function is easy. Procedural programming does not have any Object oriented programming provides proper way for hiding data so it is less data hiding so it is more secure. secure. In procedural programming, overloading is Overloading is possible in object oriented not possible. programming. In procedural programming, function is In object oriented programming, data is 13 CU IDOL SELF LEARNING MATERIAL (SLM)

Procedural oriented programming Object oriented programming more important than data. more important than function. Procedural programming is based on unreal Object oriented programming is based world. on real world. Examples: C, FORTRAN, Pascal, Basic etc. Examples: C++, Java, Python, C# etc. 1.4 DIFFERENCE BETWEEN STRUCTURE AND CLASSES A Structure is not secure and cannot hide its implementation details from the end user while a class is secure and can hide its programming and designing details. Following are the points that expound on this difference: 1) Members of a class are private by default and members of a struct are public by default. 2) When deriving a struct from a class/struct, default access-specifier for a base class/struct is public. And when deriving a class, default access specifier is private. Table 1.3 structures vs. class Basis for comparison Structure Class Basic If access specifier is not If access specifier is not declared, by default all declared, by default all member are 'public'. members are 'private'. 14 CU IDOL SELF LEARNING MATERIAL (SLM)

Basis for comparison Structure Class Declaration struct structure_name { class class_name{ type struct_element 1; data member; type struct_element 2; type struct_element 3; member function; }; . }; Instance Instance of 'structure' is Instance of a 'class' is called called 'structure variable'. 'object'. Polymorphism and Not supported Supports polymorphism and a inheritance class can also be inherited. Nature Value type Reference type Memory is allocated on Stack Heap Null values Not possible Can have null values Requires constructor and No Yes destructor 1.5 SUMMARY 15 CU IDOL SELF LEARNING MATERIAL (SLM)

 Programming practices have evolved considerably over the past few decades.  By the end of last decade, millions and millions lines of codes have been designed and implemented all over the word.  The main objective is to reuse these lines of codes. More and more software development projects were software crisis.  It is this immediate crisis that necessitated the development of object-oriented approach which supports reusability of the existing code.  Software is not manufactured. It is evolved or developed after passing through various developmental phases including study, analysis, design, implementation, and maintenance. Conventional programming using high level languages such as COBOL, FORTRAN and C is commonly known as procedures-oriented programming.  In order to Solve a problem, a hierarchical decomposition has been used to specify the tasks to be completed.  OOP is a method of designing and implementing software.  Since OOP enables you to remain close to the conceptual, higher-level model of the real-world problem, you can manage the complexity better than with approaches that force you to map the problem to fit the features of the language.  Some essential concepts that make a programming approach object-oriented are objects, classes, Data abstraction, Data encapsulation, Inheritance, Polymorphism, dynamic binding and message passing.  The data and the operation of a class can be disclosed public, protected or private. OOP provides greater programmer productivity, better quality of software and lesser maintenance cost.  Depending upon the features they support, they are classified as object based programming languages and object-oriented programming languages. 16 CU IDOL SELF LEARNING MATERIAL (SLM)

 Object oriented approach offers the most logical description of the real world. The framework of OOP encompasses all the phases of system development.  The reusability features of OOP have facilitated the rapid growth of software. 1.5KEY WORDS/ABBREVIATIONS  Classes: A class represents a set of related objects.  Data Abstraction: Abstraction refers to the act of representing essential-features without including the background details or explanations.  Data Encapsulation: The wrapping up to data and functions into a single unit (class) is known as encapsulation.  Design: The term design describes both a final software system and a process by which it is developed.  Object-oriented Programming Paradigm: The term object-oriented programming (OOP) is widely used, but experts do not seem to agree on its exact definition.  Objects: Objects are the basic run-time entities in an object-oriented system. Polymorphism: Polymorphism means the ability to take more than one form.  Alphanumeric: Pertaining to a character set that contains letters, digits, and usually other characters such as punctuation marks.  Anomaly: (IEEE) anything observed in the documentation or operation of software that deviates from expectations based on previously verified software products or reference documents. See: bug, defect, error, exception, fault. 1.6LEARNINGACTIVITY 17 CU IDOL SELF LEARNING MATERIAL (SLM)

1. Write a program in C++ to print a welcome text in a separate line. __________________________________________________________________________ __________________________________________________________________________ 2. Write a C++ program to compute the sum of the two given integer values. If the two values are the same, then return triples their sum. 1.7 UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE) A. Descriptive TypesQuestions 1. Outline the essential steps involved in carrying out a procedure-oriented programming study. 2. Identify programming language where the problem to be solved is treated as a sequence of steps? Discuss with its advantages. 3. Identify the programming where considering data as a critical element and do not allow it to flow freely around the program? Correlate with this procedural programming. 4. Identify independent entities which provide easy development and maintenance of a program correlate with function? 5. Identify data type with giving example which just specifies the structure of data? B.Multiple Choice Questions 1. How structures and classes in C++ differ? (a) In Structures, members are public by default whereas, in Classes, they are private by default (b) In Structures, members are private by default whereas, in Classes, they are public by 18 CU IDOL SELF LEARNING MATERIAL (SLM)

default 19 (c) Structures by default hide every member whereas classes do not (d) Structures cannot have private members whereas classes can have 2. What does polymorphism in OOPs mean? (a) Concept of allowing overriding of functions (b) Concept of hiding data (c) Concept of keeping things in different modules/files (d) Concept of wrapping things into a single unit 3. C++ is ______________ (a) procedural programming language (b) object-oriented programming language (c) functional programming language (d) both procedural and object-oriented programming language 4. What does modularity mean? (a) Hiding part of program (b) Subdividing program into small independent parts (c) Overriding parts of program (d) Wrapping things into single unit 5. Who invented OOP? (a) Alan Kay (b) Andrea Ferro (c) Dennis Ritchie Answers 1. (a), 2. (a), 3. (d), 4. (b) 5. (a) 1.8 REFERENCES CU IDOL SELF LEARNING MATERIAL (SLM)

 Balagurusamy E. (2001). Object Oriented Programming with C++. New Delhi: Tata McGraw- Hill.  Lafore R. (2002). Object Oriented Programming in Turbo C+ +. USA: Sams Publishing.  Schildt H. (2002). The Complete Reference in C++. New Delhi: TMH.  Kamthane (2003). Object Oriented Programming Using C++. New Delhi: Pearson Education.  http://en.wikipedia.org/wiki/Object-oriented_programming  http://www.aonaware.com/OOP1.htm  http://www.stroustrup.com/C++11FAQ.html  Lack of Black OOPS: Kobe Bryant and the difficult path of redemption  DJ Leonard, CR King - Journal of Sport and Social Issues, 2011 20 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 2 FUNDAMENTALS OF C++ 2 Structure 2.0 LearningObjectives 2.1 Introduction 2.2 Data types 2.3 Input and output stream (Cin, Cout) 2.4 Introduction to namespace 2.5 Summary 2.6 KeyWords/Abbreviations 2.7 LearningActivity 2.8 Unit End Questions (MCQ andDescriptive) 2.9 References 2.0LEARNINGOBJECTIVES After studying this unit, you will be able to:  Recognize Data types  DemonstrateInput and output stream (Cin, Cout)  Explain namespace 21 CU IDOL SELF LEARNING MATERIAL (SLM)

2.1INTRODUCTION The prime purpose of C++ programming was to add object orientation to the C programming language, which is in it one of the most powerful programming languages.The core of the pure object-oriented programming is to create an object, in code, that has certain properties and methods. While designing C++ modules, we try to see whole world in the form of objects. For example a car is an object which has certain properties such as color, number of doors, and the like. It also has certain methods such as accelerate, brake, and so on. While writing program in any language, you need to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory.You may like to store information of various data types like character, wide character, integer, floating point, double floating point, Boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory.While doing programming inane programming language e, you need to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. You may like to store information of various data types like character, wide character, integer, floating point, double floating point, boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what cane stored in the reserved memory 2.2 DATA TYPES C++ offer the programmer a rich assortment of built-in as well as user defined data types. Following table lists down seven basic C++ data types: Table 2.1 Primitive Built-in Types Type Keyword Boolean bool Character char 22 CU IDOL SELF LEARNING MATERIAL (SLM)

Integer int Floating point float Double floating point double void Valueless wchar_t Wide character Several of the basic types can be modified using one or more of these type modifiers −  signed  unsigned  short  long The following table shows the variable type, how much memory it takes to store the value in memory, and what is maximum and minimum value which can be stored in such type of variables. Table 2.2 variable type Type Typical Bit Width Typical Range char 1byte -127 to 127 or 0 to 255 unsigned char 1byte 0 to 255 signed char 1byte -127 to 127 23 CU IDOL SELF LEARNING MATERIAL (SLM)

int 4bytes -2147483648 to 2147483647 unsigned int 4bytes 0 to 4294967295 signed int 4bytes 2bytes -2147483648 to 2147483647 short int 2bytes -32768 to 32767 unsigned short int 2bytes 0 to 65,535 8bytes -32768 to 32767 signed short int 8bytes long int 8bytes -2,147,483,648 to 2,147,483,647 8bytes same as long int signed long int 8bytes unsigned long int 4bytes 0 to 4,294,967,295 -(2^63) to (2^63)-1 long long int 0 to 18,446,744,073,709,551,615 unsigned long long int ….. float 24 CU IDOL SELF LEARNING MATERIAL (SLM)

double 8bytes ……. long double 12bytes …… wchar_t 2 or 4 bytes 1 wide character The size of variables might be different from those shown in the above table, depending on the compiler and the computer you are using. Following is the example, which will produce correct size of various data types on your computer. #include<iostream> usingnamespace std; int main(){ cout <<\"Size of char : \"<<sizeof(char)<< endl; cout <<\"Size of int : \"<<sizeof(int)<< endl; cout <<\"Size of short int : \"<<sizeof(shortint)<< endl; cout <<\"Size of long int : \"<<sizeof(longint)<< endl; cout <<\"Size of float : \"<<sizeof(float)<< endl; cout <<\"Size of double : \"<<sizeof(double)<< endl; cout <<\"Size of wchar_t : \"<<sizeof(wchar_t)<< endl; return0; } This example uses endl, which inserts a new-line character after every line and << operator 25 CU IDOL SELF LEARNING MATERIAL (SLM)

is being used to pass multiple values out to the screen. We are also using sizeof () operator to get size of various data types. When the above code is compiled and executed, it produces the following result which can vary from machine to machine − Size of char:1 Size of int:4 Size of short in:2 Size of long int:4 Size of float:4 Size of double:8 Size of wchar_t:4 typedef Declarations You can create a new name for an existing type using typedef. Following is the simple syntax to define a new type using typedef − typedef type newname; For example, the following tells the compiler that feet is another name for int − typedef int feet; Now, the following declaration is perfectly legal and creates an integer variable called distance − feet distance; Enumerated Types- An enumerated type declares an optional type name and a set of zero or more identifiers that can be used as values of the type. Each enumerator is a constant whose type is the 26 CU IDOL SELF LEARNING MATERIAL (SLM)

enumeration. Creating an enumeration requires the use of the keyword enum. The general form of an enumeration type is − enum enum-name { list of names } var-list; Here, the enum-name is the enumeration's type name. The list of names is comma separated. For example, the following code defines an enumeration of colors called colors and the variable c of type color. Finally, c is assigned the value \"blue\". enum color { red, green, blue } c; c = blue; By default, the value of the first name is 0, the second name has the value 1, and the third has the value 2, and so on. But you can give a name, a specific value by adding an initializer. For example, in the following enumeration, green will have the value 5. enum color { red, green = 5, blue }; Here, blue will have a value of 6 because each name will be one greater than the one that precedes it. 2.3 INPUT AND OUTPUT STREAM (CIN, COUT) A stream is a source of sequence of bytes. A stream abstracts for input/output devices. It can be tied up with any I/O device and I/O can be performed in a uniform way. The C++ iostream library is an object-oriented implementation of this abstraction. It has a source (producer) of flow of bytes and a sink (consumer) of the bytes. The required classes for the stream I/O are defined in different library header files. To use the I/O streams in a C++ program, one must include iostream.h header file in the program. This file defines the required classes and provides the buffering. Instead of functions, the library provides operators to carry out the I/O. Two of the Stream Operators are:  <<: Stream insertion for output.  >>: Stream extraction for input. 27 CU IDOL SELF LEARNING MATERIAL (SLM)

The following streams are created and opened automatically:  cin : Standard console input (keyboard). C  out : Standard console output (screen).  cprn : Standard printer (LPT1).  cerr : Standard error output (screen). clog : Standard log (screen). caux : Standard auxiliary (screen) C++ comes with libraries that provide us with many ways for performing input and output. In C++ input and output are performed in the form of a sequence of bytes or more commonly known as streams.  Input Stream: If the direction of flow of bytes is from the device (for example, Keyboard) to the main memory then this process is called input.  Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device (display screen) then this process is called output Fig 2.1 Stream for input and output 28 CU IDOL SELF LEARNING MATERIAL (SLM)

The two keywords cout in C++ and cin in C++ are used very often for printing outputs and taking inputs respectively. These two are the most basic methods of taking input and printing output in C++. To use cin and cout in C++ one must include the header file iostream in the program Let us program use of cout,cin #include <iostream> using namespace std; int main() { char sample[] = \"GeeksforGeeks\"; cout << sample << \" - A computer science portal for geeks\"; return 0; } Output: GeeksforGeeks - A computer science portal for geeks In the above program the insertion operator (<<) inserts the value of the string variable sample followed by the string “A computer science portal for geeks” in the standard output stream cout which is then displayed on screen. #include <iostream> 29 CU IDOL SELF LEARNING MATERIAL (SLM)

using namespace std; int main() { int age; cout << \"Enter your age:\"; cin >> age; cout << \"\\nYour age is: \" << age; return 0; } Input: 18 Output: Enter your age: Your age is: 18 Header files available in C++ for Input/Output operations are:  iostream: iostream stands for standard input-output stream. This header file contains definitions to objects like cin, cout, cerr etc.  iomanip: iomanip stands for input output manipulators. The methods declared in these files are used for manipulating streams. This file contains definitions of setw, setprecision, etc.  fstream: This header file mainly describes the file stream. This header file is used to handle the data being read from a file as input or data being written into the file as output. 30 CU IDOL SELF LEARNING MATERIAL (SLM)

2.4 INTRODUCTIONS TO NAMESPACE Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names. Namespace is a feature added in C++ and not present in C.A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc.) inside it.Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope. A namespace definition begins with the keyword namespace followed by the namespace name as follows: namespace namespace_name { int x, y; // code declarations where // x and y are declared in // namespace_name's scope }  Namespace declarations appear only at global scope.  Namespace declarations can be nested within another namespace.  Namespace declarations don’t have access specifiers. (Public or private)  No need to give semicolon after the closing brace of definition of namespace.  We can split the definition of namespace over several units. 31 CU IDOL SELF LEARNING MATERIAL (SLM)

Consider following C++ program. // A program to demonstrate need of namespace int main () { int value; value = 0; double value; // Error here value = 0.0; } Output: Compiler Error:  'value' has a previous declaration as 'int value'  In each scope, a name can only represent one entity. So, there cannot be two variables with the same name in the same scope. Using namespaces, we can create two variables or member functions having the same name Classes and Namespace: Following is a simple way to create classes in a name space // A C++ program to demonstrate use of class // in a namespace #include <iostream> using namespace std; 32 CU IDOL SELF LEARNING MATERIAL (SLM)

namespace ns 33 { // A Class in a namespace class geek { public: void display() { cout << \"ns::geek::display()\\n\"; } }; } int main() { // Creating Object of geek Class ns::geek obj; obj.display(); return 0; } Output: CU IDOL SELF LEARNING MATERIAL (SLM)

ns::geek::display () 34 Example -Outside Namespace // A C++ code to demonstrate that we can define // methods outside namespace. #include <iostream> using namespace std; // Creating a namespace namespace ns { void display(); class geek { public: void display(); }; } // Defining methods of namespace void ns::geek::display() { cout << \"ns::geek::display()\\n\"; CU IDOL SELF LEARNING MATERIAL (SLM)

} void ns::display() { cout << \"ns::display()\\n\"; } // Driver code int main() { ns::geek obj; ns::display(); obj.display(); return 0; } Output: ns::display() ns::geek::display () How to Use Namespaces A supplier, say a library vendor, will present an interface to a set of services in the form of a namespace. For example: namespace my_library { // classes 35 CU IDOL SELF LEARNING MATERIAL (SLM)

// typedefs // global variable declarations // templates // global function declarations // consts // inline functions // etc. } Typically, this will be placed in a header file so that a user includes the namespace like this: #include \"my_library.h\" // use my_library To access the library facilities, the user has several choices. One can crudely and effectively make all the names from the library available in the global scope: #include \"my_library.h\" using namespace my_library; This is equivalent to a traditional #include of a header file that doesn’t use name spaces. After using namespace my_library; every name from my_library is available without qualification. If used, a name from my_library that clash with a global name cause a compile-time error unless the clash is resolved by the function and operator overloading rules. Overload resolution applies across namespaces where using-directives or using-declarations have made names accessible. A more selective approach will be taken by users who worry about name clashes, about function name resolution, or about documenting which facilities from my_library are 36 CU IDOL SELF LEARNING MATERIAL (SLM)

used. For example: 2.5 SUMMARY  C++ accomplishes input/output operations using concept of stream. A stream is a series of bytes whose value depends on the variable in which it is stored.  This way, C++ is able to treat all the input and output operations in a uniform manner. Thus, whether it is reading from a file or from the keyboard, for a C++ program it is simply a stream.  A stream is a source of sequence of bytes.  A stream abstracts for input/output devices. It can be tied up with any I/O device and I/O can be performed in a uniform way.  The C++ iostream library is an object-oriented implementation of this abstraction.  It has a source (producer) of flow of bytes and a sink (consumer) of the bytes.  The required classes for the stream I/O are defined in different library header files.  Streams can also be tied up with data files. 37 CU IDOL SELF LEARNING MATERIAL (SLM)

 Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names.  Namespace is a feature added in C++ and not present in C.  A namespace is a declarative region that provides a scope to the identifiers (names of the types, function, variables etc.) inside it.  While doing programming in any programming language, youneed to use various variables to store various information. Variables are nothing but reserved memory locations to store values. This means that whenyou create a variable you reserve some space inmemory  C++ offer the programmer a rich assortment of built-in as well as user defined data types.  Data types in C++ are categorized in three groups: Built-in, user- defined and Derived. 2.6KEY WORDS/ABBREVIATIONS  C++ iostream Library: The C++ iostream library is an object-oriented implementation of this abstraction.  Stream: A stream is a series of bytes whose value depends on the variable in which it is stored.  Unformatted Input/output: Unformatted input/output is the simplest and most efficient form of input/output.  chart: char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters 38 CU IDOL SELF LEARNING MATERIAL (SLM)

 Class: class keyword is used to declare a class.  Continue: continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition. 2.7LEARNINGACTIVITY 1.Assuming there are 7.481 gallons in a cubic foot, write a program that asks the user to enter a number of gallons, and then displays the equivalent in cubic feet __________________________________________________________________________ __________________________________________________________________________ 2. Write a program define circumference of circle with radius 2.5 __________________________________________________________________________ __________________________________________________________________________ 2.7UNIT END QUESTIONS (MCQ ANDDESCRIPTIVE) A. Descriptive Types Questions 1. Constructs C++ program that outputs the following text on screen: Oh what a happy day! Oh yes, what a happy day! 2. The following program contains several errors: Resolve the errors and run the program to test your changes. 39 CU IDOL SELF LEARNING MATERIAL (SLM)

3.Construct to print all natural numbers up to N without using semi-colon. 4.State and construct program To Swap the values of two variables without using any extra variable. 5.Identify feature which is used in C++ which declares that provides a scope to the identifiers (names of the types, function, variables etc).Illustrate with example. B. Multiple Choice Questions 1. Which keyword is used to define the user defined data types? (a) Def (b) Union (c) Typedef (d) type 2. Identify the correct statement. (a) typedef does not create different types. It only creates synonyms of existing types (b) typedef create different types (c) typedef create own types (d) typedef will not create synonyms of existing types 3. Where does a cin stops it extraction of data? 40 CU IDOL SELF LEARNING MATERIAL (SLM)

(a) By seeing a blank space (b) By seeing ( (c) By seeing a blank space & ( (d) By seeing < 4. Which is used to get the input during runtime? (a) Cout (b) Cin (c) Coi (d) cinout 5. When will the cin can start processing of input? (a) After pressing return key (b) BY pressing blank space (c) After pressing return key & BY pressing blank space (d) BY pressing delete space Answers 1. (c), 2. (a), 3. (a), 4. (b), 5. (a) 2.8REFERENCES  Venugopal, K.R. (2013), Rajkumar, Mastering C++. Tata McGraw-Hill Education  Rumbaugh J., Blaha M., Premerlani W., Eddy F., and Lorensen W., Object-oriented Modeling and Design, Prentice-Hall, 1991.  Bolshakova E., Programming Paradigms in Computer Science Education, International Journal: Information Theory & Applications, 12(3), 2005 41 CU IDOL SELF LEARNING MATERIAL (SLM)

 Herbert Schildt; The Complete Reference C++; Tata Mc Graw Hill. Object Oriented Programming with C++; Cyber tech publications.  http://www.cplusplus.com/reference/iostream/  http://www.cplusplus.com/reference/iostream/istream/getline/  https://developerinsider.co/introduction-to-cpp-cpp-programming/  An Overview of the C++ Programming Language January 1998 Bjarne Stroustrup  Programming with C++ concepts Jaakko Järvi a  Thinking in C++, Volume 1, 2nd Edition Completed January 13, 2000 Bruce Eckel, 42 CU IDOL SELF LEARNING MATERIAL (SLM)

UNIT 3 - CLASSES AND OBJECTS 1 43 Structure 3.0 LearningObjectives 3.1 Introduction 3.2 Specifying a class 3.3 Creating objects 3.3.1 Objects as Function Arguments 3.3.2 Returning Objects 3.4 Accessing classes members 3.5 Defining a member function inside and outside classes 3.6 Access Specifier 3.6.1 The Public Access Specifier 3.6.2 The Private Access Specifier 3.6.3 The Protected Access Specifier 3.7 Summary 3.8 KeyWords/Abbreviations 3.9 LearningActivity 3.10 Unit End Questions (MCQ andDescriptive) 3.11 References CU IDOL SELF LEARNING MATERIAL (SLM)

3.0LEARNINGOBJECTIVES After studying this unit, you will be able to:  Recognize how to specify a class  Define the member functions  Explain the creation of class objects  Access the class members  Discuss the access specifiers 3.1INTRODUCTION Classes and objects are at the core of object-oriented programming. Writing programs in C++ essentially means writing classes and creating objects from them. In this unit you will learn to work with the same. It is important to note the subtle differences between a class and an object, here. A class is a template that specifies different aspects of the object it models. It has no physical existence. It occupies no memory. It only defines various members (data and/or methods) that constitute the class. An object, on the other hand, is an instance of a class. It has physical existence and hence occupies memory. You can create as many objects from a class once you have defined a class.You can think of a class as a data type; and it behaves like one. Just as a data type like int, for Notes example, does not have a physical existence and does not occupy any memory until a variable of that type is declared or created; a class also does not exist physically and occupies no memory until an object of that class is created.Example: To understand the difference clearly, consider a class of vehicle and a few objects of this type as depicted below: 44 CU IDOL SELF LEARNING MATERIAL (SLM)

Fig 3.1 example illustrating class In this example vehicle is a class while car, scooter and truck are instances of the class vehicle and hence are objects of vehicle class. Each instance of the class vehicle – car, scooter and truck – are allocated individual memory spaces for the variables – reg_no, no_wheels, fuel_type, make and, color – so that they all have their own copies of these variables 3.2 SPECIFYING A CLASS Like structures a class is just another derived data-type. While structure is a group of elements of different data-type, class is a group of elements of different data-types and functions that operate on them. C++ structure can also have functions defined in it. There is very little syntactical difference between structures and classes in C++ and, therefore, they can be used interchangeably with minor modifications. Since class is a specially introduced data-type in C++, most of the C++ programmers tend to use the structures for holding only data, and classes to hold both the data and functions. A class is a way to bind the data and its associated functions together. It allows the data (and functions) to be hidden, if necessary, from external use. When defining a class, we are creating a new abstract data-type that can 45 CU IDOL SELF LEARNING MATERIAL (SLM)

be treated like any other built-in data-type. Generally, a class specification has two parts: 1. Class declaration 2. Class function definitions The class declaration describes the type and scope of its members. The class function definitions describe how the class functions are implemented. The general form of a class declaration is: class { private: variables declaration; function declarations; public: variable declaration; function declarations; }; The class declaration is similar to a struct declaration. The keyword class specifies that what follows is an abstract data of type class_name. The body of a class is enclosed within braces and terminated by a semicolon. The class body contains the declaration of variables and functions. These functions and variables are collectively called members. They are usually grouped under two sections, namely, private and public to denote which of the members are private and which of them are public. The keywords private and public are known as visibility labels. The members that have been declared as private can be accessed only from within the class. On the other hand, public members can be accessed from outside the class also. The data hiding (using private declaration) is the key feature of object-oriented 46 CU IDOL SELF LEARNING MATERIAL (SLM)

programming. The use of the keyword private is optional. By default, the members of a class are private. If both the labels are missing, then, by default, all the members are private. Such a class is completely hidden from the outside world and does not serve any purpose. Fig 3.2 Data Assess in Class The variables declared inside a class are known as data members and the functions are known as member functions. Only the member functions can have access to the private data members and private functions. However, the public members (both functions and data) can be accessed from Notes outside the class. The binding of data and functions together into a single class-type variable is referred to as encapsulation. The access to private and public members of a class is well explained diagrammatically in the Figure 3.1 Let us consider the following declaration of a class for student: 47 CU IDOL SELF LEARNING MATERIAL (SLM)

The name of the class is student. With the help of this new type identifier, we can declare instances of class student. The data members of this class are int rollno and char name [20]. The two function members are getdata () and disp(). Only these functions can access the data members. Therefore, they provide the only access to the data members from outside the class. The data members are usually declared as private and member functions as public. The member functions are only declared in the class. They shall be defined later.A class declaration for a machine may be as follows: Having defined the class, we need to create object of this class. In general, a class is a user defined data type, while an object is an instance of a class. A class provides a template, which defines the member functions and variable that are required for objects of a class type. A class must be defined prior to the class declaration. The general syntax for defining the object of a class is: 48 CU IDOL SELF LEARNING MATERIAL (SLM)

The general syntax for defining the object of a class is: Class { A class definition is very similar to a structure definition except the class definition defines the variables and functions. Consider the following program segment which declares and creates a class of objects. 49 CU IDOL SELF LEARNING MATERIAL (SLM)

student std; //std is the object of the class student In another example the employee details such as name. code, designation, address, salary age can be grouped as follows. The only difference between defining a class member function completely within its class or to include only the prototype and later its definition, is that in the first case the function will automatically be considered an inline member function by the compiler, while in the second it will be a normal (not-inline) class member function, which in fact supposes no difference in behavior. 50 CU IDOL SELF LEARNING MATERIAL (SLM)


Like this book? You can publish your book online for free in a few minutes!
Create your own flipbook