Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1...

129
C++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented programming paradigm expresses computer programs in ways that show how people perceive the world. Because programmers are people, it is only natural that our approach to the work of the world reflects pit view of the world itself. The object-oriented paradigm is built on the foundation laid by the structured programming concepts and data abstraction. Data abstraction does for data what functional abstraction does for operations. With data abstraction, data structures can be used without having to be concerned about exact details of implementation. For example, floating-point numbers are abstracted in programming languages. You are not required to know how a floating-point number is represented in binary while assigning a value to it. Likewise, you are not bothered how binary multiplication takes place while multiplying floating-point values. Abstraction for floating-point numbers has existed in programming languages since long. However, it is only recently that languages have been developed to define your own abstract data types. The fundamental change in OOP is that a program is designed around the data being operated upon rather than upon the operations themselves. This is to be expected once we appreciate that the very purpose of the program is to manipulate data. The basic idea behind object-oriented language is to combine into a single unit, both, the data and the functions that operate on the data. Such a unit is called an object. An object‟s functions, called member functions in C++, typically provide the only way to access its data. If you want to create a data item in an object, you call a member function in the object. It will read the item and return the value to you. You can‟t access the data directly. The data is hidden, so it is safe from accidental alteration. Data and its functions are encapsulated into a single entity. The Evolution of OOPS Concept : As a property of each language, there comes a point when programmers begin to have difficulty managing programs of a certain size and sophistication. Programming in an object-oriented language means creating new types of data (called classes) and

Transcript of Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1...

Page 1: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

1

Chapter - 1 OOPS INTRODUCTION

C++ PROGRAMMING

Object Oriented Programming: The object-oriented programming paradigm expresses computer programs in ways that show how people perceive the world. Because programmers are people, it is only natural that our approach to the work of the world reflects pit view of the world itself. The object-oriented paradigm is built on the foundation laid by the structured programming concepts and data abstraction. Data abstraction does for data what functional abstraction does for operations. With data abstraction, data structures can be used without having to be concerned about exact details of implementation. For example, floating-point numbers are abstracted in programming languages. You are not required to know how a floating-point number is represented in binary while assigning a value to it. Likewise, you are not bothered how binary multiplication takes place while multiplying floating-point values. Abstraction for floating-point numbers has existed in programming languages since long. However, it is only recently that languages have been developed to define your own abstract data types. The fundamental change in OOP is that a program is designed around the data being operated upon rather than upon the operations themselves. This is to be expected once we appreciate that the very purpose of the program is to manipulate data. The basic idea behind object-oriented language is to combine into a single unit, both, the data and the functions that operate on the data. Such a unit is called an object. An object‟s functions, called member functions in C++, typically provide the only way to access its data. If you want to create a data item in an object, you call a member function in the object. It will read the item and return the value to you. You can‟t access the data directly. The data is hidden, so it is safe from accidental alteration. Data and its functions are encapsulated into a single entity. The Evolution of OOPS Concept : As a property of each language, there comes a point when programmers begin to have difficulty managing programs of a certain size and sophistication. Programming in an object-oriented language means creating new types of data (called classes) and

Page 2: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

2

"teaching" those data types how to handle messages. You teach a class what to do with a "message" by creating a "method". The user creates variable of a data type(objects) or instances and sends messages to those objects. You could think of this as "Send a message to an object, and let the object figure out what to do with it". Structured Development : In traditional procedural languages large programs can be difficult to modify and maintain. The reaction to this problem was to force structure into the programs from outside through a methodology called structured development. However, they require a great deal of forethought and planning, so the project will assemble quickly and correctly, and be bug-free and easy to maintain. In traditional programming languages, normally the data is openly available for all different types of operations by the programmer, who does not have any restrictions on the data access or usage. For him the data is globally available in all corners of the program. By fault of logic he may misuse the data producing an erroneous result. Characteristics of Object-Oriented Languages: Object-oriented programming uses a vocabulary that is unfamiliar to the procedural programmer. Let us now briefly examine this vocabulary with regards to the major elements of object-oriented languages. Inheritance: OOPS permits you to create your own data types (classes) just like the types built into the language. However, unlike the built-in data types, the user-defined classes can use other classes as building blocks, using a concept called inheritance new classes can be built from the old once. The new class referred to as derived class, can inherit the data structures and functions of the original, or the base class. The new class can add data elements and functions of those it inherits from its base class. Figure below shows inheritance in C++.

Page 3: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

3

Fig. 1.1 Inheritance Reusability : Object-oriented programs are built from reusable software components. Once a class is completed and tested, it can be distributed to other programmers for use in their own programs. This is called reusability. If those programmers want to add new features or change the existing ones they can do it. The tried and tested capabilities of base classes do not need to be redeveloped. Programmers can devote time in writing new code instead of wasting time in rewriting existing code. This way software becomes easier to test since programming errors can be isolated within the new code of derived classes. Polymorphism : Polymorphism is nothing but the ability to access different implementations of the functions using the same name. There are two levels at which the Polymorphism operates: Run-time and Compile-time polymorphism.

Feature A

Feature B

Feature A Feature B

Feature C

Feature A Feature B

Feature C

Page 4: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

4

Data Abstraction : Data abstraction means you can combine the data structure and the operations on the data structure together into a new abstract data type. An abstract data type behaves just like data types that are built into language, except that they aren't part of the language definition; they are something the programmer has created. When you create a data structure in a traditional procedural language, you usually create functions to manipulate the structure. Those functions can only be used on that structure. Other functions won't know how to manipulate the structure since the structure isn't a built-in type. It makes sense then, to bind into one unit the data structure and the functions that will manipulate it. In C++ this unit is called a CLASS (also called a user-defined type). Variable or instances, of that class are called OBJECTS. Objects: In structures dividing it into functions approaches a programming problem. Unlike this, in object-oriented programming the problem is divided into objects. Thinking in terms of objects rather than functions makes the designing of program easier. Following are few candidates that can be treated as objects in different programming situations:

Employees in a payroll processing system.

Data structures like linked lists, stacks, queues etc.

GUI elements like windows, menus, icons, etc. Hardware devices like disk drive, keyboard, printer, etc. Various elements in computer games like cannons, guns, animals, etc. Customers, sales persons in a sales tracking system. Computers in a network model.

Classes: Most languages offer primitive data types like int, long and float. Their data representation and response to arithmetic, assignment and relational operators are designed as part of the language. However, the language does not know user-defined data types. The programmer defines its format and behavior by defining a class. For example, there can be user-defined data types to represent datas. The compiler and the computer do not know about dates. Programmers have to define the behavior of dates by designing a date class. This class expresses the format of date and the operations that can be performed on it . The way we can declare many variables of the primitive type int, we can define many objects of the date class. A class serves as a blueprint or a plan or a template. It specifies what data and what functions will be included in objects of that class. Defining the class doesn‟t create any variables.

Page 5: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

5

Fig. 1.2 Class contain Data and Functions

Class

Fig: 1.3 Data Encapsulation

How C++ supports OOPS : C++ was introduced to the computing fraternity by a Computer Scientist "Bjarne Stroustoup". Other languages that supports OOPS are Small talk, Prolog, Turbo Pascal V7.0, Lisp etc. Visual C++ 4.0 is the latest compiler product introduced by Microsoft. C++ has several following features that supports OOPS requirements.

Data

Functions

data 1 data 2

data 3

Func 1 ( ) Func 2 ( )

Func 3 ( )

Methods Data

d1

d2

d3

m1

m2

m3

m4

Page 6: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

6

C++ supports abstract data typing with the class construct. C++ supports inheritance. You can derive a new user-defined type from an

old one, and make changes only where you need them. C++ supports polymorphism with the virtual keyword.

These features add both power and complication to the language. As has been said by numerous authors, "If you can write bad code in C, you can write worse in C++". Or as Booch says, "Trying old techniques with a new language could be like using a power drill as a hammer, you could have a lot of bent nails and bleeding fingers". To get the most out of C++, it is incorrect to view it just as more powerful (or the next version of C.)

C++ has several features beyond C. Some of them are as follows: Overloading functions Overloading operators Conversion or automatic type conversion Inline functions Prototypes Default parameters

Exercise Explain the Concept of OOPs.

Difference between Procedural Oriented Programming Language & Object Oriented Programming Language.

C++ is the combination of __________ & ____________ Language.

C++ was invented by _____________. Give the Features of C++.

Page 7: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

7

Chapter - 2 GETTING STARTED WITH C++

Data Types : C++ recognizes the data types shown in the table below.

Type Name

Bytes

Other Names

Range of Values

int unsigned int char unsigned char short unsigned short long unsigned long enum float double long double

* * 1 1 2 2 4

4 2 4 8 10

signed, signed int unsigned signed char none short int, signed short int unsigned short int long int, signed long int unsigned long int none none none none

System dependent System dependent -128 to 127 0 to 255 -32,768 to 32,767 0 to 65,535 -2,147,483,648 to 2,147,483,647 0 to 4,294,967,295 -32,768 to 32,767 3.4E +/-38 (7 digits) 1.7E +/-308 (15 digits 1.2E+/-4932 (19 digits

C++ has four basic built-in data types. They are: char, int, float and double. Char is for storing a single character and is usually one byte in size, int stores an integral value usually two bytes long float and double stores floating point numbers. Float is for single precision numbers and double is for double precision floating point. Signed and unsigned are modifiers that can be used with any integral type. The char type is signed by default. The following are some examples of built-in data types and initialization: main() { char c; int p,q,r; float f = 156.278; double d;

Page 8: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

8

char a='a'; } Specifiers : Specifiers modify the meaning of the basic built- in types. They effectively provide a larger set of built in types. The four specifiers or qualifiers are short, long, signed, and unsigned. The long and short specifiers set the range that the data type will hold short int, int, and long int are in ascending order of range size. The actual values vary from machine to machine. Similarly, float, double, and long double are in order of increasing capacity. There is no long float and no short float or double. The signed and unsigned specifiers indicate whether the first bit of the data type is to be used as a sign indicator or no. Except for char the default is signed. Char may or may not be signed by default. The following program shows the bytes used by the different data types along with the specifiers:

#include <iostream.h> // Header file required for cout. void main() { int I; unsigned int ui; short si; //ini is understood long li; //ditto unsigned short usi; //ditto unsigned long uli; //ditto char c; unsigned char uc; float f; double d; long double ld; //cout is Console out, similar to printf cout<<"\nSize of int ="<<sizeof(I); cout<<"\nSize of unsigned int = "<<sizeof(ui); cout<<"\nSize of short int ="<<sizeof(si); cout<<"\nSize of long int ="<<sizeof(li); cout<<"\nSize of unsigned short int = "<<sizeof(usi); cout<<"\nSize of unsigned long int ="<<sizeof(uli)<<"\n"; cout<<"\nSize of char ="<<sizeof (c); cout<<"\nSize of unsigned char ="<<sizeof(uc)<<"\n"; cout<<"\nSize of float = "<<sizeof(f); cout<<"\nSize of double ="<<sizeof(d); cout<<"\nSize of long double ="<<sizeof(ld)<<"\n";

Page 9: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

9

} Constants :

The const keyword specifies that a variable's value is constant and tells the complier to prevent the programmer from modifying it. C++ Environment : The following are keywords in Microsoft C and C++. C Language Keywords :

C++ Language Keywords : class operator try virtual friend protected multiple inheritance inline public private single inheritance new this delete virtual inheritance The following are not keywords, but they have special meaning in C++. argc envp setenvp argv main set_new_handler emit setargv set_new_handler As far as syntax is concerned C language functions / keywords are subset of C++. C programs shall work in C++ compilers with "C" extensions. The C++ programs should have ".CPP" extensions. C++ has a lot of other useful features and keywords

asm fastcall self extern auto float segment based for segname break fortran short caas goto signed cdecl huge sizeof char if static const inline struct continue int switch default interrupt typedef do load union double long unsigned else near void enum pascal volatile export register while return far saverefs

Page 10: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

10

which lend a very powerful application development environment. Some features are specifically useful for Object Oriented Programming Eg.: Construction, Constructors, Destructors, Inheritance etc. Whereas some features are not OOPS specific but are very useful. Eg. : Default parameters, function Overloading etc. C++ has inherited all the properties from C, plus it has its own properties which are more enhanced. Thus there are several topics which are a part of C, but also available with C++ but not commonly used in C++. The C++ language Features to implement Object Oriented Programming Useful features The C Language Features common Features not to C and C++ used in C++ Commonly

Fig. 2.1 : The Relationship between C and C++

Escape Sequences : The escape sequences allow you to use a sequence of characters to represent special characters. Escape sequences are listed below. These escape sequences are used in I/O statements like printf(), scanf(), cout etc.

Page 11: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

11

Sequence Name Sequence Name Format Specifiers : printf (% [flags] [width] [.precision] [F | N| h | l | L } ] type ); The formats for the printf family of functions are listed below. Preprocessor Directives : The table below lists the directives to the preprocessor. Their usage and the meaning in C++ are the same as in C. Header Files :

\a Alert (bell) \b Backspace \f Formfeed \n Newline \r Carriage return \t Horizontal tab

\v Vertical tab \? Literal ? quotation mark \' Single ? quotation mark \" Double ? quotation mark \\

Backslash \ddd ASCII character in octal \xdd ASCII character in hex

d,I (signed decimal) u (unsigned decimal integer) o (unsigned octal integer) x, X (unsigned hex integer) f (fixed-point integer) e, E (scientific notation) g, G (%e or %f; whichever c (single character)

shorter s (string) p (pointer) n (character count)

#define #error #include #elif #if #line #else #ifdef #pragma #endif #ifndef #undef

Page 12: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

12

All the header files available in C are used in C++, alongwith other header files of C++. A few of them are listed below in the table. File Name Major Contents ASSERT.H Assert debugging macro BIOS.H BIOS service functions CDERR.H Common dialog error return code COLORDLG.H Common dialog color dialog's control id numbers COMMDLG.H Common dialog functions, types, and definition CONIO.H Console and port I/O routines CPL.H Control panel extension DLL definitions CTYPE.H Character classification CUSTCNTIL.H Custom Control Library header file DDE.H Dynamic Data Exchange structures and definitions DDEML.H DDEML API header file DIRECT.H Directory control DLGS.H Common dialog's dialog elements numbers DOS.H MS-DOS interface functions DRIVINIT.H Obsolete: Use print.h instead ERRONO.H errno variable definitions FCNTL.H Flags used in_open and_sopen functions FLOAT.H Constants needed by math functions FSTREAM.H Functions used by the filebuf and fstream

classes GRAPH.H Low-level graphics and font routines IO.H File-handling and low-level I/O IOMANIP.H definitions / declarations for iostream's parameterized manipulators IOS.H Functions used by the ios class IOSTREM.H Functions used by the iostream classes ISTREAM.H Functions used by the istream class LIMITS.H Ranges of integers and character types LOCALE.H Localization functions LZDOS.H Obsolete: Replaced by #define LIB#include lzexpand.h> LZEXPAND.H Public interfaces for LZEXPAND.DLL. MALLOC.H Memory-allocation functions MATH.H Floating-point-math routines

Page 13: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

13

MEMORY.H Buffer-manipulation routines MMSYSTEM.H Include file for Multimedia APIs NEW.H Declarations definitions for C++ memory

allocation functions. OLE.H OLE functions, types, and definitions OSTREAM.H Functions used by the ostream class PENWIN.H Pen Windows functions, types, and definitions PENWOEM.H Pen Windows APIs into recognizer layer PGCHART.H Presentation graphics PRINT.H Printing helper functions, types, and

definitions PROCESS.H Process-control routines SCRNSAVE.H Win3.1 screensaver definitions. SSEARCH.H Searching and sorting functions SETJMP.H Setjmp and longjmp functions SHARE.H Flags used in_sopen SHELLAPI.H SHELL.DLL functions, types, and definitions SINGNAL.H Constants used by signal function STDARG.H Macros for variable-length argument-list

functions STDDEF.H Commonly used data types and values STDIO.H Standard I/O header file STDIOSTR.H Functions used by the stdiostream and

stdiobuf classes STDLIB.H Commonly used library functions STREMB.H Functions used by the streambuf class STRESS.H Stress functions definitions STRING.H String-manipulation functions STRESTREA.H Functions used by strstream classes TIME.H General time functions TOOLHELP.H TOOLHELP.DLL functions, types, and definitions VARARGS.H Variable-length argument-list functions VER.H Version mnht. functions, types, and

definitions VMEMORY.H Virtual memory functions WFEXT.H Windows File Manager Extensions definitions WINDOWS.H Windows functions, types, and definitions WINDOWSX.H Macro APIs, window message creackes,

control APIs WINMEM32.H Function prototypes and general definition for WINMEM32.DLL Win32 bit Memory management

Page 14: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

14

SYS\LOCKING.H Flags used by locking function SYS\STAT.H File-status structures and functions SYS\TIMEB.H Time functions SYS\TYPES.H File-status and time types SYS\UTIME.H Run-time function Extensions : In C++, all the programs carry ".CPP" extensions as compared to ".C" extensions in C. Any way, even if one is working in C++ compiler and gives ".C" extension, C compiler takes over to compile that program. C++ Comments : Depending upon the requirement, they can be mentioned in either of the following ways :

1. /*begins a comment and */ ends it. 2. double-slash (//) sequence.(unless it is inside a string),everything to the end

of the current line is a comment. Program: #include <iostream.h> void main( ) { char name[20]; //This is a C++ comment cout << "Enter a name... \n"; /* This is a C comment */ cin>> name; // This is a C++ comment cout << "The name you entered was " <<name; } Operators : The table below lists C and C++ operators by category.

Arithmetic Relational + Addition < Less than - Subtraction <= Less than or equal to * Multiplication > Greater than

Page 15: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

15

/ Division >= Greater than or equal to % Modulus = = Equal != Not equal

Assignment Increment & Decrement = Assignment ++ Increment += Addition -- Decrement -= Subtraction *= Multiplication /= Division %= Modulus <<= Left shift assignment >>= Right shift assignment &= Bitwise AND ^= Bitwise exclusive OR |= Bitwise OR

Bitwise Logical

& Bitwise AND && Logical AND ^ Bitwise-exclusive- OR || Logical OR | Bitwise OR ! Logical NOT << Left shift >> Right shift ~ One's complement Pointer Conditional & Address of ?: Ternary * Indirection Miscellaneous : C++ only ( ) Function call : : Scope resolution [ ] Array element & Reference . Structure or union member .* Pointer to member -> Pointer to structure member -> Pointer to member (type) Type cast Sizeof() Size in bytes Let's run the following program. Program: #include<iostream.h> void main() { int i=10; cout<<"\n post-increment i = "<<i++; cout<<"\n pre-increment i = "<<++i; cout<<"\n post-decrement i = "<<i--; cout<<"\n pre-decrement i = "<<--i; }

Page 16: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

16

Output: post-increment i = 10 pre-increment i = 12 post-decrement i = 12 pre-decrement i = 10

Console I/O

cout :

printf is very rigid function. We have to specify each datatype with the appropriate symbol and then specify the data. The 'cout' statement instead does not take any such prototyping. An example of a cout statement is: cout<<"p"="<<p<<"National "<<str<<"\n"; Output : p=100 National Computers cin : cin is the object used for standard input .>> is used with cin. This operator waits for input that is of the same datatype that is supplied to it as argument. This is shown in the previous example. Excersice

Give the Data Types with their respective Specifiers in C++. Give the operators in C++. ____________header file is used for Console I/O in C++. Write a program to accept 2 nos. and give their addition,

subtraction, multiplication, division, & modulus.

Page 17: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

17

Page 18: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

18

Chapter - 3 C++ BASICS

Functions Definition : Functions is a set of instructions that can be used at multiple instances, but defined only once. The main() itself is a function in C and C++. The simple C program, if written in the manner below will result in an error: main() { printf("Hello Princeton\n"); } Hence in the above program, we have to include the standard header file, STDIO.H which contains the prototype of the function printf(). #include <stdio.h> main() { printf("Hell Princeton\n"); } Function Prototyping : A function prototype is declaration that defines a function and its return type, so that each time the function is called, it is checked against the prototype. It is necessary in C++. When a function prototype is declared, this template is used by the compiler when the function is called, to ensure that the proper arguments are passed to it and the return value is correct. Here is an example of a function prototype: int func_name (float arg1, double arg2, char arg3); This function will have three arguments: The first float, second a double, and third a char. It returns an integer value. It could also have been written in short as: int func_name (float, double, char);

Page 19: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

19

Let us explore a new facility in C++ which is not available in C. i.e. Default parameters. This reduces a lot of redundant coding in C++. Default Parameters : If a function is defined as accepting two integer parameters, and it is called with only one integer, it will result in an error. This can be arranged to be syntactically correct if we define initial values for the parameters. This is illustrated in the following program: Program: #include<iostream.h> void func (int a=0, int b=10) { cout <<" a=" <<a <<" b=" <<b <<"\n"; } main() { int c=100, d=300; func(c,d); func(c); func( ); } Output: a=100 b=300 a=100 b=10 a=0 b=10 While the above program will not work in C, it is error free in C++. The function func() can be called with two, one or no parameters because the missing parameter can always be used as it is initialized with some value. The program output would look like this: Thus we see that C++ behaves on three different levels with the programmer.

1) On one extreme it demands a rigid prototyping habit.

Page 20: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

20

2) On the moderate level it allows the programmer to specify default values, but when the programmer fails to define his own parameters, the default parameters help him out.

If the prototype of the above function is to be specified, it is written in the following way. void func (int, int); It would result in an error. Since the compiler first looks at the prototype default values must also be specified in the prototype declaration too. Hence the prototype must be specified thus: void func (int=0, int=10); Storage Classes There are two categories of storage classes - the declarable and the non-declarable. As in C, automatic, static and extern are the declarable storage classes. Dynamically allocated objects form a non-declarable storage class. Declarations and Definitions. Automatic : An instance(object) of a class is similar variable. Hence local variables in functions are created on the stack. The constructor is called at the point of declaration and the destructor is called when the scope (closing brace) ends. Extern : The extern keyword tells the compiler to defer allocation. An initializer is not allowed in a declaration. For example: extern int y; // Names a variable. extern const start //Names a constant. Defers storage allocation. struct person; //Names a structure type. The members // are not defined and the size of the struct is not known. For a variable, a definition provides both a name, type, memory and allows initialization.

Page 21: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

21

The extern keyword defines EXTERNAL variables. These are defined in one file and to use it in another file it should be declared thus: extern int file1_variable; Static Data Members :- The static member variable has certain special characteristics :

1) It is initialized to zero when the first object of its class is created.

2) Only one copy of that member is created for the entire class and is shared by all the objects of that class no matter how many objects are created

3) It is visible only within the class but its lifetime is the entire program.

Static variables are normally used to maintain values common to the entire class. #include<iostream.h> #include<conio.h> class test {

static int ctr; //static variable ctr int no; //normal variable no

public : void getdata(int a) {

no=a; ctr++; } void getctr(void) { cout<<”ctr=”<<ctr<<endl; } void getno(void) { cout<<”number=”<<no<<endl; } }; int test::ctr; void main() { test t1,t2,t3; //static variable ctr is initialized to zero t1.getctr(); t2.getctr(); t3.getctr();

Page 22: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

22

t1.getdata(10); t2.getdata(20); t3.getdata(30); t1.getctr(); t2.getctr(); t3.getctr(); t1.getno(); t2.getno(); t3.getno(); } OUTPUT : ctr no function() output 0 t1.getctr() ctr=0 0 t2.getctr() ctr=0 0 t3.getctr() ctr=0 1 10 t1.getdata() - 2 20 t2.getdata() - 3 30 t3.getdata() - t1.getctr() ctr=3 t2.getctr() ctr=3 t3.getctr() ctr=3 t1.getno() number=10 t2.getno() number=20 t3.getno() number=30 Static Member Functions :- Features of static member functions :-

1) A static function can have access to only other static member(function or variables)declared in the same class

2) A static member function can be called using the class name(instead of its objects) as follows :

#include <iostream.h> class test

class-name :: function-name

Page 23: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

23

{ int no; //normal variable static int ctr; //static variable

public : void setno(void) {

no=++ctr; }

void showno(void) {

cout<<”object number=”<<no<<endl; } static void showctr(void) {

cout<<”count=”<<ctr<<endl; }

}; int test :: ctr ; void main() { test t1,t2; t1.setno(); t2.setno(); test :: showctr(); test t3; t3.setno(); test :: showctr(); t1.showno(); t2.showno(); t3.showno(); } Explanation : ctr no function output 1 1 t1.setno() - 2 2 t2.setno() -

Page 24: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

24

test::showctr() count=2 3 3 t3.setno() - test::showctr() count=3 t1.showno() object number=1 t2.showno() object number=2 t3.showno() object number=3 Global : A global (extern or static) variable is alive for the entire program. It is declared above the main () in the program. Scoping : 'Scoping' rules define the blocks or file where a variable is accessible, and when it gets created or destroyed. Scope Rules Local or Block Scope : Same as in C. In C++, an object declared in a block is said to be in block scope. It is visible within the block from the point of declaration, and to all the blocks that are embedded within this block. File Scope : An object declared outside any function body, is visible from the point of declaration to the end of the file. Function scope : Variables defined in a function are seen within that function. main() {

int variable1 ; //only variable1 accessible { int variable2; //variable variable2 accessible … }

//here variable2 is destroyed //only variable 1 accessible

Page 25: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

25

} //variable 1 is destroyed here //neither variable1 nor variable2 accessible here An aspect of C++ that differs from C, and is very useful, the data can be declared on the fly. This means the declarations need not be restricted only to the start of a block. They can exist among the executable statements and sometimes also within them. Program: #include <iostream.h> int a=20; main() {

{ //this is new block

int a=5; … for (int i=0;i<10;++i) } ++a; //a can be used from outer block int b=10; //variable defined at end of block } int b=210; //this b is different from the b above} } Global : Global Variables are defined outside all of the functions blocks, and are available throughout the file and also to other files. Suppose that the following is contained in one file: The following code shows were the variables variable1, variable2, and variable3 are available and where unavailable. int globalvariable; main() { globalvariable=20; }

Page 26: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

26

In C when a local variable has the same name as a global variable in the block, the global variable is inaccessible. This handicap is overcome in C++. Using the symbol :: before the variable name indicates that the global variable is to be used, and not the local synonym. An example follows. Program: #include <stdio.h> int p = 100; //global variable main() { int p; p =50; printf("%d\n", p,::p); { int p = 25; printf("%d%\n" ,p, ::p); } } Local : Variables are defined within a block, i.e. within a function. They are 'automatic' by default. This means that they are automatically created when the function is entered, and destroyed when the function is exited. To declare a variable as automatic the word 'auto' has to precede the declaration. e.g.auto int i: Register int i : Local variables can also be declared of type 'register'. This causes the compiler to access i as fast as possible. Control Structures The statement for controlling program flow are:

if-else, while, do-while, for, break, continue, switch statement.

Since they are part of C, we will go through them only superficially.

Page 27: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

27

Accessible by any function Accessible only by function A Accessible only by function B

Function A Function B Fig. 3.1 Global and Local Variables

Global Variables

Local Variables

Local variables

Page 28: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

28

Conditional Statements

1) if-else 2) switch statement

1) if-else : The if statement will execute a body of itself when the condition is true otherwise it will execute the body of else.

Forms of if-else a) if(conditional expression)

{ statement(s) to be performed if expression is true.

}

b) if(conditional expression) { statement(s) to be performed if expression is true; } else { statement(s) to be performed if expression is false }

Page 29: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

29

Nested if-else c ) if(conditional expression) d) if(conditional expression) false false

{ true { true statement(s);

if(conditional expression) false } false else

{

true if(conditional expression)

{ false false statement(s); true false } { else false statement(s) { } statement(s); else { } statement(s); } } else

{ } statement(s); } Example : #include<iostream.h> #include<conio.h> #include<stdlib.h> void main() { int s1,s2,s3,avg; cout<<"Enter the marks of three subjects:"; cin>>s1>>s2>>s3; if(s1<35 || s2<35 || s3<35) { cout<<"The student is fail"; getch(); exit(0);

Page 30: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

30

} avg=(s1+s2+s3)/3; if(avg>=35 && avg<45) cout<<"The student is in third division"; if(avg>=45 && avg<50) cout<<"The student is in second division"; if(avg>=60 && avg<75) cout<<"The student is in first division"; if(avg>=75) cout<<"The student has got distinction"; getch(); } Switch - Case : The switch and case keywords evaluate expression and execute any statement associated with constant-expression whose value matches the initial expression. If there is no match with a constant expression, the statements associated with the default keyword are executed. If the default keyword is not used, control passes to the statement following the switch block. switch (expression) {case value1 : statement; break; case value2 : statement; break; case value3 : statement; break; (…) default : statement; } The following is a menu program the uses the switch statement: Program: #include <iostream.h>

main()

{

int esc = 0;

char inkey;

while (esc == 0)

{

cout<<"selct a,b,c, or q to quit";

cin>>inkey;

switch(inkey)

Page 31: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

31

{

case 'a':cout<<"a has been selected\n";

break;

case 'b':cout<<"b has been selected \n";

break;

case 'c':cout<<"c has been selected \n";

break;

case 'q':cout<<"I quit \n";

esc = 1;

default :cout<<"please choose only a,ba,c,q\n";

}

}

} The basic functioning of these control structures is same as in C. Loops :- The main purpose of a loop is to keep on repeating the same thing constantly. Difference Between Conditional Statements & Loops : The conditional statements executes only once. But loops can be made to execute until condition becomes false .

While Loop :- while (condition) { true

statement(s) }

#include<iostream.h> #include<conio.h> void main() { int ctr=1,no,sum=0; while(ctr<=5) { cout<<”enter one number=”<<endl; cin>>no; sum=sum+no; ctr++;

Page 32: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

32

} cout<<”sum=”<<sum; } INPUT : enter one number=2 enter one number=3 enter one number=7 enter one number=4 enter one number=9 OUTPUT : Sum=25 Explanation : ctr ctr<=5c ondition(true/false) no sum+no=sum 1 1<=5 true 2 0 + 2 =2 2 2<=5 true 3 2 + 3 =5 3 3<=5 true 7 5 + 7 =12 4 4<=5 true 4 12+4 =16 5 5<=5 true 9 16+9 =25 6 6<=5 false - - Do While :-

do { do this; } while(condition);

true

false

The Difference Between While And Do - While In while loop if the condition is true then only it will execute the body of loop . But in do-while loop first it executes the body of do and then it checks the condition from while so even if our condition false is first time still it will execute at least once. #include<iostream.h> #include<conio.h> #include<stdio.h> void main() {

Page 33: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

33

int no,sum=0; char ch; do { cout<<"enter one number="<<endl; cin>>no; sum=sum+no; cout<<"do you want to enter number again(y/n)="; fflush(stdin); cin>>ch; } while(ch=='y'); cout<<"sum="<<sum; } Input : enter one number=5 do you want to enter number again=y enter one number=8 do you want to enter number again=y enter one number=2 do you want to enter number again=n Output : Sum=15 Explanation : no no+sum=sum ch condition(true/false) 5 5 + 0 =5 „y‟ true 8 5 + 8 =13 „y‟ true 2 13+ 2 =15 „n‟ false For The for statement first initializes the loop, then tests the condition, then goes through the loop and at the end does some form of stepping. for ( initialization;expression;step ) //no semicolons { statement A………} for(initialisations ;condition ;increment/decrement )

Page 34: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

34

false { true false do this; } The expression is evaluated before each iteration and executes the statement only if true. At the end of the loop the step is executed. Any of the above expressions - initialization, expression, step or statement may be empty. for (;i<10;) The for loop is usually used for counting purpose. Inside a loop, the flow can be controlled using break and continue. To quit the loop at any point use the break keyword. Continue skips over the rest of the statements in the loop, and goes on to the next iteration. For example look at two loops: for(i=0;;++i) { statements…….. if ( i==100 ) break; statements…… } Here the loop will execute infinitely if it were not for the break statement which causes exit from the loop at he 101 st iteration Nested For Loop :

for(initialize;condition;increment/decrement) false true { for(initialize;condition;increment/decrement) false

{ true do this ;

Page 35: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

35

false } }

Example : #include<iostream.h> #include<conio.h> #include<stdio.h> void main() { int row,col; for(row=1;row<=3;row++) { for(col=row;col<=3;col++)

{ printf(“*”); } printf(“\n”);

} getch(); }

Output : * * * * * * Explanation : row row<=3 condition col col<=3 condition output 1 1<=3 true 1 1<=3 true *

2 2<=3 true * 3 3<=3 true * 4 4<=3 false No Output(“\n”) 2 2<=3 true 2 2<=3 true * 3 3<=3 true * 4 4<=3 false No Output(“\n”) 3 3<=3 true 3 3<=3 true *

Page 36: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

36

4 4<=3 false No Output(“\n”)

4 4<=3 false - - - - Exercise

Explain Static data member & functions. Explain all the control structures with examples? Explain all the loops with examples? Write a program in C++ to print the Fibonacci series? Write a program in C++ to get all the prime numbers from 1

to 100? Write a program to print as shown below?

1 21 321 4321 54321 4321 321 21 1 if the number entered by the user is 5.

Chapter -4 CLASSES AND OBJECTS

Structures : A structure is a collection of data of similar or different data types. It can represent a record. Creating structure : On creating a structure a new datatype is defined. This definition creates a new datatype for future use. Variables of this data type can be then declared and used like the basic data types. For example, if the details of a student is to be stored, the following structure is used. struct StudentDetail { int RollNum; char Name [40]; int Marks [6];

Page 37: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

37

float Percent; char Grade; }; Example: struct StudentDetail { int RollNum; char Name [40]; int Marks [6]; float Percent; char Grade; }s [50]; struct Object1; The keyword struct is used to define the structure Object1. The user-defined name StudentDetail is a tag, which is used at the time of declaring a structure variable. the above examples give the declaration and initialization of structures, structure pointers and structure arrays. The first example declares only one structure to store details of an individual student, whereas the second declares an array of structure to store detail of 50 students of the entire class. Data Encapsulation : Consider the structure, struct number

{ public: int p;

} ; The keyword public makes p available to all those who knowingly or unknowingly use it. It is not guarded from outside interference. Any statement can now use it as though it were just another structure member. Similarly struct number {

private: int p; }

Page 38: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

38

The 'private' protects the variable p, restricting its use to its private zone, and thus ensuring that even accidentally the data cannot be touched or tampered with. This is the concept of Data Encapsulation. Class and Objects : Definition : A Class is an abstract datatype which contains data and the functions that access that data. An Object is an instance of a class. Here we are not concerned about how the addition of two complex numbers is taking place. We are only concerned about the fact that adding two complex numbers adds their real parts and their imaginary parts respectively. The actual operations on the data is hidden. These operations are done by Methods. These methods are the member functions of the class that operate on the data. The picture of the Class and the Objects is shown in the fig. Class Object Object

Data

Member Function

Member Function

Data

Member Function

Member Function

Data

Member Function

Member Function

Page 39: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

39

Fig 4.1: The Object -oriented Paradigm Let us study one more example in detail to understand the classes better. Program: #include <stdio.h> #include <iostream.h> class number { private: int p; public: void display(void) { p = 100; printf("%d\n" ,p); } }; void main() { number n; n.display(); } Output: 100 Here we have a class, tagged number, having a private member, p, and a public function, display ( ). Through this function we can access the private member of the structure, although in a restricted manner. This is called Data Abstraction. Access specifiers : There are four access specifiers, of which two are of interest here. Private : Every attribute and member function declared between a private keyword and the next access specifier or the end of the class is hidden from the users of the class. They are however accessible to member functions of the class itself. In the example class number above, p is private and not accessible to the users of the class number, except for the function display.

Page 40: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

40

Public : Every attribute and member function declared between the public keyword and the end of the class is available to the user as well as member functions of the class itself. In the example class number above, member function display is public and hence can be accessed by users of this class. Program: #include <stdio.h> #include <iostream.h> class integer { private : int i; public: void print(void) { i=10; printf("PUBLIC FUNCTION ACCESSING PRIVATE MEMBER i=%d" ,i); } }; void main(void) { integer num; num.print(); } Output: PUBLIC FUNCTION ACCESSING PRIVATE MEMBER I=10 Data Hiding : The private and public sections of a class are given by the keywords "private" and "public" respectively. All the variables and the functions declared in a class, whether in the private section, are the member if the class. The keywords - private and public - in a class determine the accesibility of class members. However, a program can access the private members of a class only by using the public member functions of the class as shown in the figure below. This insulation of data members from direct access in a program is called as INFORMATION HIDING or DATA HIDING.

Page 41: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

41

PROGRAM: #include <iostream.h> #include <stdio.h> class A { private: int x; public : void set(int b) { x= b ; } void print() { cout <<x<<"\n"; } //iostream.h used }; main() { A object1,object2; //two objects created object1.set(105); object1.print(); object2.set(60); object2.print(); getchar(); //stdio.h used } Output : 105 60 Private Not accessible from outside class

Data or Functions

Page 42: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

42

Public Accessible outside class

Fig. 4.2: Private and Public

Data Abstraction : It helps in separating the computer's view of data from that of a human. In other words, data abstraction represents information in terms of its interface with the user. Once the data structure has been designed, functions can be defined to operate on it. These functions can be stand alone functions like the traditional C language functions or functions declared in that structure. This bundling together of data and the functions that operate on that data is called as DATA ENCAPSULATION. First level Abstraction : In the diagram we see that the programmer cannot see the real data, but can only access the data in a very specific manner using the Methods. In the figure the four data items can be accessed in only six different ways using six Methods. Second level Abstraction : We can have more than one layer between the programmer and the data as shown in the fig. This is called Second layer of Abstraction. Data is private and can be accessed by three private methods which in turn are accessed by other three public methods by the programmer. Here it is called two layered Data Abstraction. Methods private public

m1

m2

m3

m4

d1

d2

Page 43: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

43

Data Encapsulated Fig. 4.3 Single level Abstraction I level Abstraction II level Abstraction

Data Methods Methods Programmer private private public layer 1 layer 2

Fig. 4.4 Multilevel Abstraction. Object : A class is a user- defined data type and an object is an instance of a class. Data members of different objects belonging to the same class occupy different memory areas, but function members of different objects of the same class share the same set of functions. A data item that belongs to a class is an object. Int, float, char and double can be called classes and the corresponding variables their objects. Method :

data

data

data

m1

m2

m3

MA

MB

MC

m5

m6

d3

d4

Page 44: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

44

Is a function associated with an object. To "send a message' to an object means to use a methods of that object. In the above example display is a method. It accesses the private data p. The data items and the functions (methods) of a class together are termed as MEMBERS of the class. Every class acts as a SERVER TO THE OTHERS THAT USE IT. A class can be used in one of three ways:

1. By explicitly declaring a variable of the given class type. 2. By making a class contain the given class. 3. By inheriting from a given class (see chapter on inheritance).

Client Server Concept : The user is called the CLIENT. The client and server are said to follow a PROTOCOL. The server satisfies the protocol by providing the services( or calls or methods) it offers and the client satisfies the protocol by requesting only those services (or calling or messaging for) that have been offered. The terminology we would use is, that A CLIENT MESSAGES THE SERVER, AND IN REPONSE THE SERVER EXECUTES A METHOD. The server may execute a method by calling a member function or by retrieving an attribute. In order to execute a method, the server class may have to access some attributes and other member functions, which it would not like to offer as services to the user. They form implementation details that the user need not know about. In fact, the server may change the implementation without informing the user, provided it satisfies the class protocol (or interface). This is known as INFORMATION HIDING and leads to ENCAPSULATION. Lets face OOPS with one more example: Program: #include <iostream.h> class Distance // Distance class { private: // Hidden Data int feet; float inches; public: void initdist(int ft, float in) // set distance {

Page 45: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

45

feet = ft; inches = in; } void getdist() // get Length from user { cout <<"\nenter feet: "; cin >> feet; cout <<"\nEnter inches: "; cin >> inches; } void showdist() // display distance { cout << feet <<"--"<< inches <<"\n" ; } }; void main() { Distance dist1, dist2; // define two lengths dist1.initdist(11,6.25); // set dist 1 dist2.getdist(); // get dist2 from user // display lengths cout <<"\ndist1 ="; dist1.showdist(); cout <<"\ndist2 = "; dist2.showdist(); } Here: Distance is a class. dist 1,dist 2 are objects of class Distance. initdist (), getdist() and showdist() are methods that acesses. feet and indhes which is the private data. "this" pointer : When a method is invoked a pointer is passed to it which identifies the one object (among the many objects that may belong to the same class) that we want to use. This pointer is called 'this'. The built in pointer, 'this', points to the object being processed. #include <iostream.h> class number { private: int p; public: void assign(int q)

Page 46: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

46

{ this->p=q; } void display (void) { cout <<this->p<<"\n"; } }; void main() { number n,m; //multiple onjects of the same calss n.assign(100); m.assign(200); n.display(); m.display(); } Output: 100 200 this

Fig. 4.5 This Pointer In this program even though objects n and m are used alternately, the 'this' pointer directs the processing to the right object.

Arrays Of Objects #include<iostream.h> #include<conio.h> class employee

data

data

method

method

Pointer

Page 47: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

47

{ int age; char name[15]; public : void getdata(void); void putdata(void); }; void employee :: getdata(void) { cout<<"Enter name="<<endl; cin>>name; cout<<"Enter age="<<endl; cin>>age; } void employee :: putdata(void) { cout<<"Name="<<name<<endl; cout<<"Age="<<age<<endl; } void main() { employee manager[3]; //Array of object for(int i=0;i<3;i++) { cout<<"\n Details of manager :"<<i+1<<"\n"; manager[i].getdata(); } for(i=0;i<3;i++) { cout<<"\n Manager :"<<i+1<<"\n"; manager[i].putdata(); } } Interactive Input : Program Output : Details of manager :1 Manager :1 Enter name=kashyap Name=kashyap Enter age=23 Age=23 Details of manager :2 Manager :2 Enter name=Bhushan Name=Bhushan Enter age=25 Age=25

Page 48: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

48

Details of manager :3 Manager :3 Enter name=Mitesh Name=Mitesh Enter age=22 Age=22 Objects as Function Arguments Like any other data type, an object may be used as a function argument. This can be done in two ways :

1) A copy of the entire object is passed to the function. 2) Only the address of the object is transferred to the function.

Example : #include<conio.h> #include<iostream.h> class time { int hr,min; public : void gettime(int h,int m) { hr=h; min=m; } void puttime(void) { cout<<hr<<"hours and "; cout<<min<<"minutes "<<"\n"; } void sum(time , time); //objects are arguments }; void time :: sum(time t1,time t2) //t1 and t2 are objects { hr=t1.hr+t2.hr; min=t1.min+t2.min; while(min>59) { min=min-60; hr=hr+1; } } void main()

Page 49: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

49

{ time t1,t2,t3; t1.gettime(2,45); t2.gettime(3,30); t3.sum(t1,t2); //t3=t1+t2 t1.puttime(); //display t1 t2.puttime(); //display t2 t3.puttime(); //display t3 } OUTPUT : 2 hours and 45 minutes 3 hours and 30 minutes 6 hours and 15 minutes hr 6 t1.hr 2 t2.hr 3 min 15 t1.min 45 t2.min 30 (t1+t2)

t3.sum(t1 , t2) Friend Functions : Friend function possesses certain special characteristics :

a) It is not in the scope of the class to which it has been declared as friend. b) Since it is not in the scope of the class, it cannot be called using the object of

that class. It can not be invoked like a normal function without the help of any object.

c) Unlike member function, it cannot access the member names directly and has to use an object name and dot membership operator with each member name.(e.g. A.x).

d) Usally, it has object as arguments. Example :- #include<iostream.h>

Page 50: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

50

#include<conio.h> class B; //Forward declaration class A { int a; public : void seta() { cout<<"enter first number="<<endl; cin>>a; } void friend max(A,B); }; class B { int b; public : void setb() { cout<<"enter second number="<<endl; cin>>b; } void friend max(A,B); }; void max(A a1 , B b1) //Definition of friend function { if(a1.a>b1.b) cout<<"first number is greater"; if(a1.a<b1.b) cout<<"second number is greater"; if(a1.a==b1.b) cout<<"both numbers are equal"; } void main() { A a2; a2.seta(); B b2; b2.setb(); max(a2,b2); } Returning Objects : A function can not only receive objects as arguments but also can return objects to another function.

Page 51: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

51

Example : #include<iostream.h> #include<conio.h> class complex //x+iy form { float x; // real part float y; //imaginary part public : void input(float real , float imag) { x=real; y=imag; } friend complex sum(complex , complex); void show(complex); }; complex sum(complex c1, complex c2) { complex c3; //object c3 is created c3.x=c1.x+c2.x; c3.y=c1.y+c2.y; return(c3); } void complex :: show(complex c) { cout<<c.x<<"+ j"<<c.y<<"\n"; } void main() { complex A,B,C; A.input(3.1 , 5.65); B.input(2.75,1.2); C=sum(A,B); //C=A+B; cout<<"A=";A.show(A); cout<<"B=";B.show(B); cout<<"C=";C.show(C); } Output : A=3.1+j5.65 B=2.75+j1.2

Page 52: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

52

C=5.85+j6.85

Exercise

Explain classes & objects with example? A member declared as _______ can be accessed anywhere

in the program whereas ________ can be accessed only within the class.

Explain data abstraction with its various levels? Explain this pointer with example? Explain friend functions with example? Create two classes DM & DB which store the value of

distances. DM stores distances in meters and centimeters and DB in feet and inches. Write a program that can read values for the class objects and add one object DM with another object of DB.

Use a friend function to carry out the addition operation. The object that stores the results may be a DM object or DB object, depending on the units in which the result are required. The display should be in the format of feet and inches or meters and centimeters depending on the object on display.

Chapter - 5 POLYMORPHISM

Function Overloading : Definition : When several different function declarations are specified for a single name in the same scope, that function is said to be overloaded. When that name is used, the correct functions is selected by comparing the types of the actual arguments with the types of the formal arguments.

Page 53: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

53

Explanation : In C, if in the same scope we had two function definitions with the same name, it would be an error. Thus if we wanted to display a char, a float and an int, we would have to write three functions: one accepting a char argument, one a float and one an int. Each function would have to be given a different name and we would have to remember three names just to display some variable. If we had a lot of datatypes, the list of names would grow so long. C++, however, allows the functions to be differentiated, not only by their names, but also by the datatypes of their arguments. Thus different functions can be called by the same name and different argument datatypes. Program : #include <stdio.h> void print(char *a) { printf("%s\n",a); } void print(int a) { printf("%d\n",a); } void print(float d) { printf("%f\n",d); } main() { char *s= "National Computers"; int i = 100; float f = 123456.78; print(f); print(s); print(i); } Output : 123456.78 National Computers 100

Page 54: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

54

This feature is called function overloading. Another point about function overloading is that the compiler differentiates the functions according to their argument types and Not according to their return types. Thus the following prototypes will not be acceptable: int sum (float, float); float sum (float, float); Overloading Rules : In order to match the arguments and make a call, C++ follows rules:

1. Exact match. 2. int to double conversion. 3. Any user defined conversion i.e. provided as constructors for the user defined

class taking single parameter as a reference to another user defined or inbuilt type or as conversion functions.

print (float) print (char) print (int)

___________ ___________ ___________ print (f); ___________ ___________ ___________ print (s)

___________ ___________ ___________ print (i); ___________ ___________ ___________

Page 55: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

55

Fig. 5.1 Overloaded Functions Functions that CANNOT be overloaded :

1. Functions that differ only in the return type. 2. Member functions that differ only in, that one is static member and other

isn't. 3. Functions that differ by an argument being a pointer (*) versus an array([ ]). 4. Overloading is defined in the same scope and not across scopes. Note the

following example: int f(char*); void g() { extern int f (int); //hides earlier declaration. They // are in different scopes.

f ("abc"); // invalid, as function is not overridden but // hidden, hence not seen. }

Member functions of two different classes may have the same name as the default parameter would differ. Strictly speaking, these functions are in different (class) scopes.

Inline Functions :

C++ allows functions to be defined with a new keyword inline. Inline functions, unlike conventional functions, do not result in a call to a single functions; rather, the code for the inline function expands in place wherever the function is used. To inline a function the programmer adds the keyword inline in front of the definition.

inline min(int n1, int n2) { return (n1<n2) ? n1 : n2; }

The inline functions are faster as the compiler just picks the code and thus slower stack operations are obviated. Unlike MACROS, they are part of the C++ language and are not processed by the preprocessor.

Page 56: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

56

Strings :

The string manipulation routines allow you to compare strings, copy them, search for strings and characters, and perform various other operations. All the functions of strings that are valid in C are all valid in C++. To have an access to all the functions listed below, one has to include "string.h" header file.

Routine Description

Strcat, fstrcat Append one string to another strchr, fstrchr Find first occurrence of character in String strcmComp fstrcmp Compare two strings strcpy, fstrcpy Copy one string to another String strcspm, fstrcsn Find first occurrence of a character

from set strdup, fstrdup Duplicate a string sterror Maps an error number to a message

string sterror Maps user-defined error message

string stricmp, fstricmp Compare two strings without regard to

case strlen, fstrlen Find length of string strwr, fstrlwr Covert string to lowercase strncat, fstrncat Append characters of a string strncmp, fstrncmp Compare characters of two strings strncpy, fstrncpy Copy characters of one string to

another strnicmp, fstrnicmp Compare two strings w/o regard to

case strnset, fstrnset Set characters of a string to a given

character strpbek, fstrpbrk Find first occurrence character from

string in another strchr, fstrrchr Find last occurrence of character in

string strrev, fstrrev Reverse a string strset, fstrset Set all characters to a given character strstr, fstrstr Find first occurrence of string in

another string strupr, fstrupr Convert a string to uppercase

Page 57: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

57

Input / Output In C++, there are facilities for performing input and output known as streams. Cout : The Standard Output Stream: cout The name cout represents the standard output stream. You can use cout to display information: #include <iostream.h> void main(0) { count << "Hello, world\n";} The string Hello, word\n is sent to the standard output device, which is the screen. The << operator is called the insertion operator. It points from what is being sent (the string) to where is going (the screen). Suppose you want to print an integer instead of a string. In C, you would use printf with a format string that describes the parameters: printf(%d", amount ); The program sends three different data types to cout; a string literal, the integer amount variable, and a character constant '.' to add a period to the end of the sentence. Notice how multiple values are displayed using a single statement. The << operator is repeated for each value. Formatted Output : So far, the examples haven't sent formatted output to cout. Suppose you want to display an integer using hexadecimal instead of decimal notation. The prinf function handles this well. How does cout do it? Let's face it. Program: #include <iostream.h> main() { int amount = 123; cout <<dec << amount <<' ' << oct << amount <<' ' << hex << amount;

Page 58: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

58

} Output: 123 173 7b The example inserts each of the manipulators (dec, oct, and hex) to convert the value in amount into different representations. Each of the values shown is a different representation of the decimal value 123 from the amount variable. Let us take one example to see all different types of datatypes and the streams. Program: #include <iostream.h> main() { int i = 65535U; cout << "i =" << i << "\n"; long int l = 42294967295L; cout <<"l =" << l << "\n"; cout << "i = " << unsigned(i) <<"\n"; cout << "l = " << ( unsigned long ) l << "\n"; } Cin : The standard Input Stream: cin At times you may want to read data from the keyboard. C++ includes its own version of standard input in the form of cin. The next example shows you how to use cin to read an integer from the keyboard. Program: #include <iostream.h> void main() { int amount; cout << "Enter an amount... \n"; cin >> amount; cout << "The amount you entered was " << amount; }

Page 59: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

59

This example prompts you to enter an amount. Then cin sends the value that enter to the variable amount. The next statement displays the amount using cout to demonstrate that the cin to read other data types as well. The next example shows how to read a string from the keyboard. Program; #include <iostream.h> void main() { char name[20]; cout << "Enter a name... \n"; cin >> name; cout <<"The name you entered was " << name; } The approach shown in this example has a serious flaw. The character array is only 20 characters long. If you type too many characters, the stack overflows and peculiar things happen. The get function solves this problem. For now, the examples assume that you will not type more characters than a string can accept. Common Manipulators Stream Format Control Functions :

Manipulator Member Function Description

Dec Hex Oct

setfill( c) setprecision(c)

setw(n)

flags(10) flags(16) flags(8)

fill(c) precision (c)

width(n)

Set radix to 10 Set radix to 16 set radix to 8

Set the fill char'r to c Set display precision to c

set field width

The Standard Error Stream: cerr To send output to the standard error device, use cerr instead of cout. You can use this technique to send messages to the screen from programs that have their standard output redirected to another file or device. Now format flag values for the stream. The values are specified by the following bit masks (ios enumerators) that can be combined using the bitwise-OR ( | ) operator. The following program shows different overloaded methods of cout, used extensively for output formatting.

Page 60: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

60

Program: #include <iomanip.h> #include <iostream.h> main() { cout.setf(ios::right|ios::showpoint|ios::fixed); cout.precision(2); cout.width(20); cout<<500000.0 << "\n"; } The following table shows the details of methods associated with cout. They all are part of the basic class ios.

Page 61: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

61

Value Meaning

ios::skips Skip white space on input

ios::left Left-align values; pad on the right with the fill character

ios::right Right-align values; pad on the left with the fill character.

ios::internal Add fill characters after any leading sign or base indication

ios::dec Format numeric values as base 10 (decimal)

iosoct Format numeric values as base 8 (octal)

ios::hex Format numeric values as base 16

ios::showbase Display numeric constants in a format that can be read by the C++ compiler.

ios::showpoint Show decimal point and trailing zeros for floating-point

values.

ios::uppercase Display uppercase A-F for hex values and E for scientific

ios::showpos Show plus signs(+) for positive values.

ios::scientific Display floating-point numbers in scientific format.

ios::fixed Display floating-point numbers in fixed format.

Page 62: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

62

The class heirarchy is shown below in the class tree.

Fig. 5.2 Class ios Manipulators : There are two types of Manipulators: Input and Output Manipulators allow you to add functions into the streams itself reducing the code. One has to include the <iomanip.h> file to implement these manipulators. Program :

ios

istream ostream

isstream ofstream

istream_withassign

iostream stream_withas

sign ifstream

strstream fstream stdiostream

streambuf

filebuf

strstreambuf

stdiobuf

iostream_init

ostream

Page 63: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

63

#include <iostream.h> #include <iomanip.h> ostream & setup(ostream &st) { st.setf(ios::left); st << setw(10) << setfill ('$'); return st; } main() { cout <<10<< " " <<setup << 10; } Output: 10 10$$$$$$$$

Exercise

Explain polymorphism, with example. Explain all the string manipulation functions. Explain the manipulators with a program.

Write a program to calculate the simple interest the default interest rate is 2.5(using default value of arguments of function).

Chapter - 6 CONSTRUCTORS AND DESTRUCTORS

Page 64: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

64

Constructors Definition : A 'Constructor' is a method that has the same name as its class and is automatically executed only at the time of declaration of an object of the class. A constructor cannot be invoked by a user or explicitly called. Consider the following program on a simple constructor. Program : #include <iostream.h> class C1 { private: int p,q; public: C1 (int a =0, int b=0) { p=a; q=b; } int add (int a) { return (p+q+a); } int add (C1 a) { return (p+a.p+q+a.q); } void display (void) { cout <<p<<" "<<q<<"\n"; } }; main() { C1 n,m(200); n.display(); m.display(); int I=n.add(10); cout<<I<<"\n"; int j=n.add(m); cout<<j<<"\n";

Page 65: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

65

} Output: 0 0 200 0 10 200 What a Constructor Does ? A constructor performs various tasks that are not visible to you as the programmer, even if you write no code for the constructor. These tasks are all associated with building a complete and correct instance of class type. Constructors are called at the point an object is created. Objects are created as:

1. Global (file-scoped or externally linked) objects. 2. Local objects, within a function or smaller enclosing block. 3. Dynamic objects, using new operator allocates an object on the program heap

or "free store". 4. Temporary objects created by explicitly calling a constructor. 5. Temporary objects created implicitly by the compiler. 6. Data members of another class. Creating objects of class type, where the class

type is composed of other class-type variables, causes each object in the class to be created.

7. Base class sub-object of a class. Creating objects of derived class type causes the base class components to be created.

Types of Constructors : C++ defines two special kinds of constructors, default and copy constructors.

1. Default Constructor : It can be called with no arguments. It Construct a default object of the class

types. However, you can declare a default constructor with an argument list, provided all arguments have default.

2. Copy Constructor : It can accept a single argument of reference to same class type. Copy objects

of the class type. Copy constructors must be declared in such a way that they can accept a single argument of reference to the same class type. More arguments can be supplied, provided all subsequent arguments have default.

Page 66: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

66

3. Explicitly Called Constructor : Constructors can be explicitly called in a program to create objects of a given

type. For example, to create two Point objects that describe the ends of a line, the following code can be written: DrawLine( Point 13, 22), Point( 87, 91 );

Two objects of type Point are created, passed to the function DrawLine, and destroyed at the end of the expression (the function cal). Another context in which a constructor is explicitly called is in an initialization: Point pt = Point( 7, 11 ); An object of type Point is created an initialized using the constructor that accepts two arguments if type of type int. Constructor Overloading Like other functions, however, constructors can be overloaded. A class can have more than one constructor. Each one should differ from the other by the type of parameters. There is no upper limit. The C++ compiler (being a strict type checker), would call the correct constructor automatically by matching the types of the parameters. One of the beast uses of this is to convert (or coerce) more than one related type. The constructor can specify the parameters to be given to the member objects constructors (called the member initialization list). This is required, as members would be assumed to be created when the constructors of the containing class is executed. Thus, the constructors of member objects are called before the constructor of the main class is executed. Class object1(20),object2(20); The Copy constructor Is the name suggests, A copy constructor is one which allows to create an object of a given class from another of the same class. a copy constructor takes on argument that of type reference the class. Initialization is performed when the object is being created (i.e it does not fully exist as yet). The copy constructor is used for initialization, when the initial value is an object of the same class. For example, assuming the copy constructor and the assignment operator were defined for the class vector. vector v1 (10); // calls constructor taking an int as parameter.

Page 67: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

67

vector v21=v1; // copy constructor called. vector v3 (10); v3 = v2 // overloaded assignment operator called. Let us see program on copy constructor. Program : #include<iostream.h> class code { int id; public: code(){} code(int a){id=a;} code(code &x) {id=x.id;} void display() { cout<<id; } }; void main() { code A(100); code B(A); code C=A; code D; D=A; cout<<"\nid of A:"; A.display(); cout<<"\nid of B:"; B.display(); cout<<"\nid of C:"; C.display(); cout<<"\nid of D:"; D.display(); } Output: id of A:100 id of B:100 id of C:100 id of D:100 Destructor

Page 68: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

68

A 'Destructor' is a method that has the same name as the class, but preceded by a tilde (-) mark. A destructor is executed at the time of destroying the object, and cannot be invoked by us or explicitly called. "Destructor" functions are the inverse of constructor functions. They are called when objects are destroyed (deallocated). The destructor is commonly used to "clean up" when an object is no longer necessary. Consider the following declaration of a String class. The destructor for class String is declared as - String(). Class String { public: String(char*ch); //Declare constructor ~String(): // and destructor. private: char*_text; } Let us see how a constructor and a destructor face each other in a same program and how they are declared. Program : #include<iostream.h> class C1 { private: int p; public: C1 (void) { p=100; cout<<"\n Constructor.p="<<p; } C1 (int q) { p=100; cout<<"\n Int Constructor.p="<<p; } void display (void) { p=300; cout<<"\nDisplay.p=" << p << "\n"; }

Page 69: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

69

~C1(void) { cout<<"\nDestructor"; } }; void main() { C1 n,m(200); n.display(); m.display(); } Output: Constructor.p=100 Int Constructor.q=200 Display.p=300 Display.p=300 Destructor. Destructor. Rules for Constructors / Destructor :

1. C++ unlike C, allows automatic variables to be declared anywhere in the function. This saves program memory.

2. The parameters to be given to the constructor should be specified at the time

of instantiation. The destructor does not have any such syntax support, as it cannot take any parameters.

3. The return types of the constructor and destructor functions are never

specified. Like any other member function, the body of the constructor and destructor can be outside the class definition (with the class qualifier as for any other member function), but the prototype should be within the class definition body.

4. Unlike other member functions, the constructor should not be called

explicitly by the user. This is because, a constructor differs from all other nonstatic member functions of its class in that a constructor is NOT called for an object of its class; instead it is called for a chunk or raw memory which has to be converted to an object of the type of its class.

5. The destructor can be explicitly called by the user, but with the or-> syntax

otherwise it would call the tilde operator and inverse the result of the

Page 70: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

70

function. One should not call the destructor until it is required - typically for hardware addresses that are never deallocated, as they begin at a specific predetermined address.

Exercise

Explain constructors and its types. Explain destructors, is it necessary to use destructors. Give a program using both constructors & destructors.

State whether true or false: 1. Constructors, like other member functions, can be

declared anywhere in the class. 2. Constructors do not have any return types. 3. A class should have at least one constructor. 4. Destructors never take any arguments.

Page 71: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

71

Chapter - 7 POINTERS

Definition : Pointers are variables that carry addresses of memory locations that contain data of a particular type. It should be noted that a pointer need not be initialized at the time of definition as the following example might suggest. The program illustrates some types of pointer to variables: class Class { }; void main() { unsigned char uc; unsinged char*ucp=&uc; long double ld; long double *ldp;

const int ci= 10; const int*cip=&p; Class C; Class*Cp=&C;

} Void Pointer : Different pointers may be of different sizes internally. Void pointers also exist. A void pointer means a pointer to any data type. The use of the keyword void to describe a pointer is different from its use to describe function argument lists and return values. Thus function that is declared thus: func 1 (void*ptr) { … } can accept a pointer to any data type. Thus in this case the function calls: func 1 (&c); and func 1 (&d); where c and d are of type char and double respectively, are valid. Since different pointers may be of different sizes, the void pointer will be at lleast as large as the largest typed pointer, so as to be able to accommodate any pointer, inside the function however, we need to know what kind of pointer was C1. One method that could be used is illustrated in the following program:

Page 72: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

72

Program: #include<iostream.h> enum dtype{ chartype, inttype, floattype}; void display (void* ptr, dtype whichtype ) { switch (whichtype) { case inttype : cout<<"int="<<*( (int*)ptr )<< "\n"; break; case chartype : cout<<"char="<<(*( ( char * )ptr ))<<"\n"; break; case floattype : cout<<"float ="<<*( (float *)ptr )<<"\n"; break; } } void main() { int i =100; char c ='C'; float f = 123.456; display( &i, inttype); display( &c, chartype); display( &f, floattype); } Pointers have four main uses :

Arrays

Function arguments

Direct memory access,

Dynamic memory allocation.

Page 73: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

73

Pointer and Arrays An array is actually just another type of pointer. Thus we can use an array just as we would use a pointer. An array can be declared as follows: char array_name[100]; This declares an array of 100 characters, from array_name[0] to array_name[90]. we can now say: *array_name ="A string is an array of characters" Remember that when a string is used it is actually a pointer to it that is being used. In the above statement the pointer to the string is assigned to the pointer to the array. Thus now the pointer to the array is pointing to the string. This has the effect of assigning the string to the array. Program: #include <iostream.h> char array[ ] = { 'a','b','c','d','e','f','g' }; void main() { for (int i=0;i<7;++i) cout<<"array["<<i<<"]="<<array[i]<<'\n'; char * cp = array; for (int i=0;i<7; ++i) cout<<"i= "<<i<<"*(cp+i)="<<*(cp+i)<<"\n"; for (int i=0;i<7; ++i) cp[i]=(cp[i]+7); for (int i=0; i<7; ++i) cout<<"array["<<i<<"] ="<<array[i]<<"\n"; } Output

array[0]=a array[1]=b array[2]=c array[3]=d array[4]=e

Page 74: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

74

array[5]=f array[6]=g i=0*(cp+i)=a i=1*(cp+i)=b i=2*(cp+i)=c i=3*(cp+i)=d i=4*(cp+i)=e i=5*(cp+i)=f i=6*(cp+i)=g array[0]=h array[1]=i array[2]=j array[3]=k array[4]=l array[5]=m array[6]=n

This program shows that a pointer to the starting address of an array can be treated like the array itself. Once the pointer cp is assigned to the starting address of array, the pointer can be used instead of the array itself. char *cp is the same as cp[], if the array isn't external. When cp[i] is assigned a new value, the array[i] is also assigned. In the next program there is a demonstration of array indexing. It shows three different ways of selecting the zeroth element, and prints the array using pointer addition. Program: #include <iostream.h> void main() { int arr[20]; for (int i=0; i<20; i++) arr[i] = 200 - i*i; cout<<"arr[0]="<<arr[0]<<"\n"; cout<<"*(arr+0) ="<<*(arr+0)<<"\n"; cout<<"*arr ="<<*arr<<"\n"; for(int i=0;i<20;i++) cout<<"*(arr + " <<i <<") ="<<*(arr+i)<<"\n"; } A definition of the type int array [ ] = {45,23,36,46,13,35,98,76,74 } ;

Page 75: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

75

creates a global array and also initializes it to the values given. This is called aggregate initialization. You can treat it as an array, for example; void func() { char *str = "NATIONAL COMPUTERS.\n"; cout<<str[2]; } Output: An array of pointers is very useful construct. An example of this is the second argument that the main function can take: char*argv[]; or char**argv; The following example takes command line arguments and concatenates them. Program : #include <iostream.h> void main(int argc, char*argv[]) { char buffer[100]; char*bufptr=buffer; for( int i=0;i<argc; i++) for (char *ptr=argv[i]; *ptr ;ptr++) *bufptr++ = *ptr; *bufptr = 0; // this terminates the string cout<<buffer<<"\n"; } This program creates a character buffer to hold the finished string, defines a pointer, assigns it to the starting address of the buffer, and uses it to stuff characters into the buffer. Pointers in Function arguments : When you want a function to change the value of any of its arguments when it returns, you should declare a pointer to the variable as argument instead of declaring the variable itself. When a variable is declared as argument i is actually copied onto a local variable inside the function and any changes made to that variable in that

Page 76: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

76

function are destroyed along with the local variable so the changes do not affect the original variable. On the other hand if a pointer to a variable within the function changes are made to the actual variable and so the modifications are preserved. Thus in the following code i will be 10 at the first printf() statement and i will be 20 at the next. Program:

#include<iostream.h> #include<conio.h> void swap(int &a, int &b) { int t=a; a=b; b=t; } void main() { int x=10,y=20; cout<<”x:”<<x<<” y:”<<y; swap(x,y); cout<<”x:”<<x<<” y:”<<y; } output: x:10 y:20 x:20 y:10 Here the & operator is used to declare the address of the variable i to the function. The & is a unary operator that returns the memory address of the variable it is prefixed to. Direct Memory access Sometimes we would like to access memory directly. Examples of this is the video memory in PC's and memory mapped I/O in some computers. Sometimes it is possible to determine the size of some object or group of objects, only at run time. So these objects cannot be defined beforehand. These objects can be created at run time by using the 'new' keyword, which returns the address of the allocated memory that can be assigned to a pointer and used. This process is called dynamic memory allocation.

Page 77: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

77

Ex: char far *ptr=0xb8000000; This is the far pointer to the video ram. Dynamic Memory Allocation New Operator : The new operator attempts to dynamically allocate ( at run time) one o more objects of type-name. The new operator cannot be used to allocate a function; however, it can be used to allocate a pointer to a function. For example: float(*cp) [25][10]; cp=new float[10][25][10]; The definition of cp allocates a pointer to an array of type float with dimensions [25] [10]. It does not allocate an array of pointers. All array dimensions but the leftmost must be constant expressions that evaluate to positive values; the leftmost array dimension can be any expression that evaluates to a positive value. Lifetime of New Objects : Objects allocated with the new operator are not destroyed when then scope in which they are defined is exited. Because the new operator returns a pointer to the objects it allocates, the program must define a pointer with suitable scope to access those object. Example: int main() { // Use new operator to allocate an array of 20 characters. char *An Array = new char[20]; for(int I = 0; I<20;++)

{ // On the first iteration of the loop, allocate // another array of 20 characters. if(i = =0 ) {

char*AnotherArray =new char[20]; }

Page 78: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

78

… }

delete AnotherArray; // Error:pointer out of scope. delete AnArray; // OK: pointer still in scope. } Once the pointer Another Array goes out of scope in the example above, the object can no longer be deleted. Initializing New Objects: An optional new-initializer field is included in the syntax for the new operator. This allows new objects to be initialized with user-defined constructors. The following example illustrates how to use an initialization expression with the new operator: Program: #include<iostream.h> class Acct { public: // Define default constructor and a constructor that accepts // an initial balance. Acct() { balance = 70.5; } Acct(double init_balance) { balance = init_balance;} private: double balance; }; int main() { Acct* CheckingAcct=new Acct(); Acct* savingsAcct=new Acct (34.98); double* HowMuch= new double (43.0); return 0; } Delete Operator

Page 79: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

79

The delete operator deallocates an object created with the new operator. The delete operator has result of type void and therefore does not return a value. The operand to delete must be a pointer returned by the new operator. How delete Works : The delete operator deallocates an object created with the new operator. The delete operator has a result of type void and therefore does not return a value. The operand to delete must be a pointer returned by the new operator. int main() { // Allocate a user-defined object. // of type double on the free store using the new operator. ClassA*ptrObject = new ClassA; double *dObject = new double; … // Delete the two objects. delete ptrObject: delete dObject;

… return 0; } Let us see an example on new and delete with strings. Program: #include<iostream.h> #include<string.h> // required by strlen, and strcpy class String { private: char *str; // A traditional string int size; // Size of str buffer public: String(const char *s); ~String(); void print() { cout <<str; }

Page 80: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

80

}; String::String(const char *s) { size = strlen(s); str = new char[size + 1]; strcpy(str,s); } String::~String() { delete str; } void main() { String s("String should be easy to use.\n"); s.print(); } Pointer arithmetic Pointer arithmetic depends on the type of pointer being used. Suppose a pointer is pointing to one integer in an array of integers, then the pointer incremented by 1 will point to the next integer in the array and not the next memory location. The following program demonstrates pointer arithmetic.

Page 81: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

81

Program: #include<iostream.h> void main() { double d = 123.456, *dp1 =&d, *dp2; char c = 'A' ,*cp1 =&c, *cp2; dp2 = dp1+1; cp2 = cp1+1; cout<<"cp2-cp1 ="<<cp2-cp1<<"n"; cout<<"dp2-dp1 = "<<dp2-dp1<<"\n"; cout<<"(int)cp2-(int)cp1 ="<<(int)cp2-(int)cp1<<"\n"; cout<<"(int)dp2-(int)dp1 ="<<(int)dp2-(int)dp1<<"\n\n"; cout<<"cp2=cp1,dp2=dp1,(cp2--)--,(dp2++)++.\n"; cp2=cp1; dp2=dp1; (cp2--); (cp2--); (dp2++); (dp2++); cout<<"cp1-cp2 ="<<cp1-cp2<<"\n"; cout<<"dp1-dp2 ="<<dp1-dp2<<"\n"; cout<<"(int)cp1-(int)cp2 ="<<(int)cp1-(int)cp2<<"\n"; cout<<"(int)dp1-(int)dp2 ="<<(int)dp1-(int)dp2<<"\n"; } Here you might expect that subtracting two adjacent doubles might result in 8, but it would result in 1, signifying the number of double variable between two adjacent double addresses. Pointers Examples : The size of a pointer depends on the size of the address. The Intel 80 x 86 microprocessors, on which he IBM PCs are based, use a segmented addressing scheme in which the addresses consist of a segment and its offset. The size of a pointer in this scheme depends on the memory model selected during compilation. Some programs are small and don't need mush data space. Pointers Examples : We will go through some examples of pointer use. The first one reads the standard input and counts all the various kinds of characters and displays the numbers of occurrences of each kind of character at the end.

Page 82: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

82

Program : #include <streams.h> #include <limits.h> void main() { int statistics[CHAR_MAX + 1]; char c; for(int i=0; i<CHAR_MAX; i++)

statistics[i]=0; //initialize array while (cin.get(c) //for each char input statistics[c]++; //use char as index; increment count

for(i=0;i<CHAR_MAX;i++) if(staatistics[i]) cout<<"number of" <<i<<"."<<chr(i)<<":"<<statistics[i]<<"\n";

}

Check out the output for yourself on the computer. The next program is an example of how to pass arguments of unknown size. Here a pointer has to be passed. The two approaches possible are shown. Program : #include<iostream.h> void dispa( const int a[ ], int arraysize) { for (int i=0;i<arraysize; i++) cout <<"a["<<i<<"]="<<a[i]<<"\n"; } void dispb( const int b[ ] ) { for ( int i=0; b[i]!=1;i++) //let-1 terminate the array cout<<"b["<<i<<"]="<<b[i]<<"\n"; } int c[] = { 43,69,57,47,38,49,-1}; void main() { dispa( c, sizeof(c)/sizeof(c[0]));//no.of elements are

Page 83: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

83

//calculated using the given division dispb(c); } Since the arrays are declared as pointers, the function may be able to modify the array. Hence the arguments are defined as const. Pointers and structures : The next example demonstrates the C ling of struct and object pointers. When you C1 a pointer to a structure or an object, you must dereference the pointer in a special way, using the structure pointer operator (->). The operator * refers to the entire structure, so you can't select individual members using *. The following example demonstrates what happens when you dereference an entire structure using the *, instead of individual elements using->. Program: #include <stdio.h> #define PRINT(a) printf (#a"=%d\n",a) struct st { float f; int p,q,r; }; void main() { st x,y; st *ptx=&x,*pty=&y; x.f=0.0;x.p=x.q =y.r=56; ptx=pty; //this dereferences the structure PRINT(x.p); PRINT(x.q); PRINT(x.r); printf("x.f=%f\n",x.f); } The program shows that the entire structure is copied from y to x. Referencing : A reference is like giving another name for a variable. The statement,

Page 84: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

84

int &a=b; Says that a is a reference to b. The concept is similar to a pointer. If b is changed so will a, and vice versa. Referencing eliminates the star sing we use while using pointers. In pointers we 'de-reference' the pointer when we want to use its target variable. With references we just use the reference as though it were the variable itself. A program will introduce us to the concept of referencing. Program: #include<stdio.h> void main() { int a=5; int&b=a; printf("a=%d, b=%d.\n",a,b); a=100; printf("a=%d, b=%d.\n" ,a,b); printf("addr of a=%u, b=%u.\n",&a,&b); } Out put : a=5 b=5

a=100 b=100 a=101, b=101. addr of a=65500,65500. Constants and References : The keyword 'const' used in a data definition, makes the data invulnerable change. The following statement gives the integer p, a value 50, and makes it value unchangeable throughout the program: const int p=50; This is equivalent to the statement; int const p=50; Note that the integer has to be initialized at the time of definition and at that time only. The following program illustrates the const keyword. Program : #include<stdio.h>

Page 85: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

85

void main() { const int p = 50; const int& a = p; printf("p=%d a=%d\n",p,a); } Output : p=50 a=50 Here is an erratic program: #include <stdio.h> void main() { char *const p ="Sam is a fox"; printf('%s\n",p); p="Jam in a box"; printf("%s\n",p); } Program: #include <stdio.h> class C1 { int p,q,r; public: C1(int u=0, int v=0,int w=0) { p=u; q=v; r=w; } C1 byvalue(C1 A); C1 bypointer (C1 *A); C1 byreference(C1& A); void display (char* msg =" ") { printf("%s:p=%d q=%d r=%d\n",msg,p,q,r); } };

Page 86: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

86

C1 C1::byvalue(C1 A) { A.p=A.q=A.r=468; return (A); } C1 C1::bypointer( C1* A) { A->p= A->q= A->r=349; return *A; } C1 C1::byreference(C1& A) { A.p= A.q= A.r= 198; return A; } void main() { C1 A,B; A.byvalue(B).display("by value"); A.bypointer(&B).display("by pointer"); A.byreference(B).display("by reference"); } Exercise

Explain pointers in C++. Explain passing by reference in C++.

Explain the operators which are used for dynamic allocation & de-allocation of memory.

Explain pointers and structures in C++.

Fill in the blanks: 1. _____ operator is used allocate memory & ________ is

used to de-allocate the memory. 2. If an integer pointer is incremented then the value of the

pointer increases by ___ why ____________________. 3. ____ operator is used to get the value at address.

Page 87: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

87

Chapter - 8 OPERATOR OVERLOADING

Operator Overloading In fact, C++ allows declaration of overloading operators as a function. In order to understand what is meant by overloading operators, consider any operator as a function. All rules that apply to function overloading apply to operators as well. Differences : Overloading Operator And Overloading Function :- The number of arguments for a given operator are predefined (1 for unary, 2 for binary and 3 for tertiary). An overloaded operator may appear in the operator‟s natural form rather than the function call form. The following operators can be overloaded

The unary forms of the following operators can be overloaded as well + - * & The following operators cannot be overloaded

. * :: ? : Rules for Operator Overloading

new delete + - * / % ^ & | ~ ! = < > += -= *= /= &= ^= &= |= << >> >>= <<= = = != <= >= && || ++ -- , ->* -> () [ ]

Page 88: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

88

Operators must either be class member functions or take an argument that is of class or enumerated type or arguments that are references to class or enumerated types.

1. Operators obey the precedence, grouping, and number of operands dictated by their typical use with built-in types. Therefore, there is no way to express the concept "add 2 and 3 to an object of type Point," expecting to be added to the x co-ordinate and 3 to be added to they co-ordinate.

2. Unary operators if declared as member functions take no arguments; if declared as global functions, they take one argument. Binary operators if declared as member functions take one argument; if declared as global functions, they take two arguments.

3. Overloaded operators cannot have default arguments. 4. All overloaded operators except assignment (operator=) are inherited by

derived classes. 5. The first argument for member-function overloaded operators is always of

the class type of the object for which the operator is invoked. Example : #include<iostream.h> class time { int hr,min; public : void gettime(int h,int m) { hr=h; min=m; } void puttime(void) { cout<<hr<<"hours and"; cout<<min<<"minutes" <<"\n"; } time operator+(time t1) //objects are arguments { time t; //object t is created t.hr=hr+t1.hr; t.min=min+t1.min; while(t.min>59) { t.hr=t.hr+1; t.min=t.min-60; }

Page 89: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

89

return(t); //returning object(values of t.hr & t.min) } }; void main() { time t2,t3,t4; t2.gettime(2,45); t3.gettime(3,30); t4=t2+t3; //invokes operator+() cout<<"t2=";t2.puttime(); //display t1 cout<<"t3=";t3.puttime(); //display t2 cout<<"t4=";t4.puttime(); //display t3 } OUTPUT : t2=2 hours and 45 minutes t3=3 hours and 30 minutes t4=6 hours and 15 minutes time operator +(time t1) { time t; t 6 t.hr = t1.hr (3) + hr (2) ; 6.20 t.min = t1.min (30) + min (45) ; return (t); return

t2 t3 2 hr 3 hr 45 min 30 min Friendships Definition : The friend keyword allows programmers to designate either the specific functions or the classes whose functions can access not only public members but also protected and private members. In some circumstances, it is more convenient to grant member

Page 90: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

90

level access to functions that are not members of a class or to all functions ion a separate lass. Member Functions and Classes as Friends : Class member functions can be declared as friends in other classes as shown. class A {

private: int_a; friend int B::Func1(a); // Grant friend access to one function in

class B. } class B { public: int Func 1(A a ) { return a._a; } // OK: this is a friend. int Func 2(A a ) { return a._a } // Error: _a is private member. }; In the preceding example, only the function B::Func1 (A) is granted friend access to class A. Therefore, access to the private member_a is correct in function b of class B but not in function c. For example, if there were a class branch_manager, which should be allowed to see into the details of the class account, then we should have the following declaration within the class definition; friend class branch_manager; Friend Functions Friend functions are not considered class members; they are normal external functions that are given special access privileges. Friends are not in the class's scope, and they are not called using the member-selection operators (.and ->) unless they are members of another class. The following example shows a Point class and an overloaded operator, operator+. (This example primarily illustrates friends, not overloaded operators.) Program; // Header file for point class

Page 91: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

91

#if !defined(_I_POINT_H_) #define _I_POINT_H_ #include<conio.h> class Point { int x,y; public: Point( int u, int v ) : x(u),y(v) { } Point() { x=0; y=0;} void print() { cprintf("x->%5d y->%5d\r\n",x,y); } Point operator +(Point p) { return Point(x+p.x, y+p.y); } Point operator -(Point p) { return Point(x+p.x,y+p.y); } void putch(char c) { gotoxy(x,y); ::putch(c); } int operator <=(Point p) { return x<=p.x && y<=p.y; } int operator >(Point p) { return (x>p.x && y>p.y); } int operator <(Point p) { return (x<p.x && y<p.y); } int operator ==(Point p) {

Page 92: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

92

return (x==p.x && y==p.y); } Point operator +=(Point p) { return Point(x+=p.x, y+=p.y); } int getx() { return x; } int gety() { return y; } }; #endif //End of Point.h header file. The main program goes like this: #include <conio.h> #include "point.h" class Rectangle { protected: Point origin,corner; public: Rectangle(Point p, Point q) : origin(p), corner(q) { } // ctor initializer void print() { origin.print(); corner.print(); } void draw(); }; enum Frame { TopLeft=218,Top=196,TopRight=191, Left=179,Right=179, BottomLeft=192,Bottom=196,BottomRight=217 }; void Rectangle::draw() {

Page 93: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

93

Point p = origin; //top p.putch(TopLeft); for ( p+= Point(1,0); p<corner; p+=Point(1,0)) p.putch(Top); p.putch(TopRight); //right for (p+=Point(0,1); p<(corner+Point(1,0));p+=Point(0,1)) p.putch (Right); // bottom p.putch(BottomRight); for (p+=Point(-1,0);p>origin;p+=Point(-1,0)) p.putch(Bottom); p.putch(BottomLeft); // left for (p+=Point(0,-1);p>(origin-Point(1,0));p+=Point(0,1)) p.putch(Left); } class Window : public Rectangle { public: Window(Point p, Point q) : Rectangle(p,q) { } void select() { Window(Point(origin.getx()+1, origin.gety()+1), Point(corner.getx()-1, corner.gety()-1)); } void fullScreen() { Window(Point(1,1),Point(80,25)); } void open () { select(); clrscr(); fullScreen(); draw();

Page 94: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

94

select(); } void close (); void print () { cprintf("%5d%5d%5d%5d ", origin.getx(),origin.gety(), corner.getx(),corner.gety()); } friend Window& operator <<(Window& w, char *s); }; Window& operator<<(Window& w, char*s) { cputs(s);return w; } main() { clrscr(); Rectangle r1(Point(5,2), Point(40,12)); r1.draw(); gotoxy( 1,15); r1.print(); Window w1 (Point(6,3), Point(41,13)); w1.open(); w1.fullScreen(); gotoxy(1,18); w1.print(); w1.select(); for (int i=0; i<100;i++) w1 <<"Here is"<<" the last line\n"; fullscreen(); gotoxy(1,24); } Try the above program and Discuss the Output. Friends and Manipulators ;

Page 95: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

95

Manipulators can also be designed for strings in the similar fashion as we design for other datatypes. The following example defines a class string with constructors, destructors and friend manipulators. Note that the class contains only the prototypes and the definitions are declared after the class declaration. Program; #include <iostream.h> #include <string.h> // required by strlen, and strcpy class String { private: char*str; // A traditional string int size; // Size of str buffer public: String(const char*s); ~String(); friend ostream &operator<<(ostream &os, const String &s); }; String::String(const char*s) { size = strlen(s); str=new char[size + 1]; strcpy(str,s); } String::~String() { delete str; } ostream & operator<<(ostream &os, const String & s) { return os<<s.str; } main() { String s("make efficient use of memory"); cout <<"strings should also\n" <<s <<"\n"

Page 96: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

96

<<"and be reuseable.\n"; }

Exercise Explain operator overloading with an example.

All the operators can be overloaded, yes or no. Justify? Explain the rules of operator overloading? Explain friend functions. Create a class Complex which has two floats real &

imaginary, two functions getcomplex() and putcomplex() which will get the complex number from the user & print the complex number in the console & also an overloaded operator + to add the two complex number. Create 3 objects of class complex accept two complex from the user using the getcomplex() function, add the two complex & store it in the third complex number and display all the three complex number using the putcomplex() function. Example: Number1=1.5+3i Number2=1.7+2.1i Number1+Number2=3.2+5.1i Where i is root of -1.

Page 97: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

97

Chapter - 9 INHERITANCE

Definition : The mechanism of deriving a new class from an old class is called inheritance .The old class is referred to as the base class and the new one is called the derived class Reusability feature can be achieved with the help of inheritance.It means we can use something that already exists rather than trying to create the same all over again.It would not only save the time and money but also reduce frustration and increase reliability. Public and Private Inheritance : With inheritance, there are three types of 'users' of a given class,

a) When an object of the given class type is created. b) When an attribute of the given class type is used in another class. c) When another class inherits from the given class.

The Protected keyword Concept

Here Class B is inheriting from class B. Suppose there is private member int x in class A, then as we know that private member is available only within the class. Therefore int x will be visible only within the class A, but if we want int x to be available in class B then we have only one alternative left i.e. we have to declare int x as public, but this will break the concept of data encapsulation, which is the main feature of OOP language. So for that we have the third and final access specifier protected. If a member of a class is declared as protected then this member is not only available inside the class but also in the class which is inheriting from it. Protected Member Access :

A

B

Page 98: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

98

Class members declared as protected can be used only the following:

1. Member functions of the class that originally declared these members. 2. Friends of the class that originally declared these members. 3. Classes derived with public or protected assess from the class that originally

declared these members. 4. Privately derived classes that also have private access to protocted members.

Forms Of Inheritance :

1) Single inheritance : A derived class with only one base class is called single inheritance .

A (Base class) B (Derived class) Example :-

#include<iostream.h> class A { int c; //private not inheritable public : int a,b; //public will be inherited void getno() { a=10,b=20; } void sub() { c=b-a; cout<<"substraction="<<c<<endl; } }; class B : public A { int p,q; public : void add() { p=a+b;

Page 99: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

99

cout<<"addition="<<p<<endl; } void mult() { q=a*b; cout<<"multiplication="<<q<<endl; } }; void main() { B b1; b1.getno(); b1.sub(); b1.add(); b1.mult(); b1.a=30; b1.b=15; int z=b1.a/b1.b; cout<<"division="<<z; } OUTPUT : subtraction=10 addition=30 multiplication=200 division=2 DESCRIPTION : class A class B : public A private section private section int c int p,q public section public section int a,b add() getno() Inherited mult() sub() from A

int a,b getno() sub() The class B ia a public derivation of the base class A.Therefore, B inherits all the public members of A and retains their visibility. Thus public member of the base class

Page 100: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

100

A is also a public member of the derived class B.The private member of A cannot be inherited by B.

2). In private derivation, the public members of the base class become private members of the derived class

class A class B : private B

private section private section int p,q int c

public section int p,q int p,q getno() getno() sub() sub()

public section add() mult()

The membership of the derived class B is shown in above Figure. In private derivation, the public member of the base class become private members of the derived class . Therefore, the objects of class B can not direct access to the public member functions of B. MULTILEVEL INHERITANCE :- Base class Grandfather Derived class form A Father & Base class for B Derived class Child Definition :- The mechanism of deriving a class from another derived class is known as multilevel inheritance . Example :- #include<iostream.h>

A

B

C

Page 101: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

101

class A { protected : int x; public :void setx(void) { x=10; cout<<"x="<<x<<endl; } }; class B : public A { int b,c; public : void setb(void) { b=10; cout<<"b="<<b<<endl; } void add(void) { c=b+x; cout<<"c="<<c<<endl; } }; class C : public B { int y,z; public :void sety(void) { y=20; cout<<"y="<<y<<endl; z=x*y; cout<<"z="<<z<<endl; } }; int main() { C c1,c2; c1.setx(); c1.setb(); c1.add(); c1.sety(); }

Page 102: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

102

OUTPUT : x=10 b=10 c=20 y=20 z=200 DESCRIPTION : Class A Class B : public A Class C : public B protected section private section private section int x int b,c; int y,z public section public section public section setx() setb() sety() add() setx() setb() add() setx() Class B is a public derivation of base class A, Hence B inherits all the public members of A and retains their visibility but cannot inherit private members of A. Class B inturns serves as base class for C. Hence C inherits all public members of B and hence of A. Class B is known as intermediate base class. The chain A-B-C is known as inheritance path. MULTIPLE INHERITANCE :- A derived class with more than one base class is called as multiple inheritance . (base class1) (base class2) (base class n) ……

(derived class) EXAMPLE : #include<iostream.h> class A { protected : int a; public : void seta()

B B-2 B-n

D

Page 103: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

103

{ a=10; cout<<"a="<<a<<endl; } }; class B { protected : int b; public : void setb() { b=10; cout<<"b="<<b<<endl; } }; class C : public A , public B { int sum; public : void tot() { sum=a+b; cout<<"sum="<<sum<<endl; } }; void main() { C c1; c1.seta(); c1.setb(); c1.tot(); } Description : class A class B protected section protected section int a int b public section public section seta() setb()

Page 104: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

104

class C : public A,public B private section int sum public section tot() seta() setb() In case of multiple inheritance, a single class may inherit the public properties more than one base classes, as shown figure. For eg. A child may have its physical structure (first property) from its father (first base class) and the intelligence (second property) from his mother (second base class). Hybrid Inheritance :- It is the combination of multiple as well as multilevel inheritance.

Example : #include<iostream.h> #include<conio.h> class A { protected : int rollno; public : void getno(int a) {

A

B

D

C

Page 105: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

105

rollno=a; } void putno(void) { cout<<"Roll No="<<rollno<<"\n"; } }; class B : public A { protected : float part1,part2; public : void getmarks(float x , float y) { part1=x; part2=y; } void putmarks(void) { cout<<"Marks obtained="<<"\n" <<"part1="<<part1<<"\n" <<"part2="<<part2<<"\n"; } }; class C { protected : float score; public : void getscore(float s) { score=s; } void putscore(void) { cout<<"sports wt="<<score<<"\n"; } }; class D : public B , public C { float total; public : void display(void) { total=part1+part2+score; putno(); putmarks();

Page 106: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

106

putscore(); cout<<"Total Score="<<total<<"\n"; } }; void main() { D d1; d1.getno(1480); d1.getmarks(35.5 , 42.5); d1.getscore(8.2); d1.display(); } OUTPUT : Roll No=1480 Marks Obtained= Part1=35.5 Part2=42.5 Sports wt=8.2 Total Score=86.2

Page 107: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

107

DESCRIPTION : class A class B : public A class C f

class D : public B ,public C

Here, as in fig., Class A serves as base class for Class B, Hence B inherits all public properties of A. Also class B serves as base class for class D which is a case of multilevel inheritance. Also Class C is the base class for D, a case if Multiple Inheritance. Hence Class D inherits all the public properties of class A, B and C. This is hybrid Inheritance. Where two or more types of inheritance are used in a single program. Abstract Classes A class is said to be abstract if it is used only for the purpose of inheritance i.e. if it is only used for creating subclasses. One cannot create an object of an abstract class. Note that it is just a programming concept, it helps a programmer in developing a hierarchy of classes. Constructors / Destructors and Inheritance :

protected section

float score

public section

public section

protected section int rollno

getno() putno()

public section

protected section

float part1, part2

getmarks() putmarks()

getno() putno()

getscore() putscore()

private section float total

public section

display()

getmarks() putmarks()

getno() putno()

getscore() putscore()

Page 108: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

108

Constructors : C++ assumes that the constructors of the base class to be called before the constructor for the derived class is executed. If the parameters to the base class is not specified, the default constructor (one without any parameters) if it exists would be called. The constructor for a derived class can specify parameters of only its immediate base class. When an object is defined in the derived class, first the constructor of the base class is called, and then the constructor of the derived class. The following program shows that the constructor goes from the base, down the hierarchy. Program; #include<iostream.h> class ClassA { public: ClassA(void) { cout<<"constructor.ClassA\n"; } }; class ClassB : ClassA { public: ClassB(void) { cout<<"Constructor.ClassB\n"; } }; class ClassC : ClassB { public: ClassC(void) { cout<<"Constructor.ClassC\n"; } };

Page 109: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

109

main() { ClassA a; cout<<"\n"; ClassB b; cout<<"\n"; ClassC c; } Output : Constructor. ClassA Constructor. ClassA Constructor. ClassB Constructor. ClassA constructor .ClassB Constructor. ClassC Destructors and inheritance : The destructor goes in reverse order, from the derived class up to the base class. When an object of class savings_account goes out of scope, the destrucotr of class saving_account is executed first, followed by that of its base class-class account. No special syntax is requited for destructors as they cannot be overloaded and cannot have parameters. Program: #include <iostream.h> class ClassA { public: ClassA (void) { cout<<"Constructor.ClasA\n"; } ~ClassA(void ) { cout<<"Destructor. ClassA\n"; } };

Page 110: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

110

class ClassB : ClassA { public: ClassB() { cout<<"Constructor. ClassB\n"; } ~ClassB(void) { cout<<"Destrucot.classB\n"; } }; class ClassC :ClassB { public: ClassC(void) { cout<<"Constructor. ClassC\n"; } ~ClassC(void) { cout<<"Destructor. ClassC\n"; } }; main() { ClassA a; cout<<"\n"; ClassB b; cout<<"\n"; ClassC c; } Output: Constructor. ClassA Constructor. ClassA Constructor. ClassB

Page 111: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

111

Constructor. ClassA Constructor. ClassB Constructor. ClassC destructor. ClassC destructor. ClassB destructor. ClassA destructor. ClassB destructor. ClassA destructor. ClassA Local Classes : Classes the are declared within a function are local to the scope of that function. In the example given below the class 'loc' is local to the function func(), It behaves like any other local variable. It is inexistant when the functions is exited. The destructor is called a the end of the function scope. Program: #include <iostream.h> void func(void) { class loc { int p; public: void print(void) { p=100; cout<<p<<"\n"; } }a1; a1.print(); } main() { func(); }

Page 112: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

112

display() Pointers and Inheritance Pointer to Objects : Just like other datatypes, we can also have pointers to the objects. In the example, put is a pointer pointing declared to point to an object of class. Ex: class *ptr; Lets study at a program to understand Pointers with Inheritance. Program: #include <iostream.h> class room { int count; public: void students (void) { count=50; cout<<count<<"\n"; } }; main() { room *Tenth; Tenth = new room(); Tenth -> students(); }

Here Tenth is a pointer to a class - room. Hence the symbol -> is used to call a method of the class - students(). Pointers with Hierarchy : Let us how a pointer behaves in an inheritance hierarchy #include <iostream.h> class ClassA

Page 113: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

113

{ public: void display(void) { cout<<"clasA\n"; } }; class ClassB : public ClassA { public: void display(void) { cout<<"ClassB\n"; } }; class ClassC : public ClassB { public: void display(void) { cout<<"ClassC\n"; } }; main() { ClassA *p; ClassA a; ClassB b; ClassC c; p = &a ; p->display(); p = &b ; p->display(); p = &c ; p->display(); } Output :

Page 114: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

114

ClassA

ClassA ClassA But this is not what we wanted. We recall that when methods that have the same name in the base and derived classes are accessed directly through the derived class objects, the methods of the derived class overrides the method of the base class. But pointers behave differently. Even of the pointer is assigned a different address, it will continue to aces the methods of the base class. The is vivid in the above output. The problem can be solved by type casting the pointer. When the pointer is casted to access a derived class. it need not even be passed the address of the derived class. At the time of casting itself, it accesses the object of the derived class. Casting pointers : Let us now rewrite the program with casting pointers to get the desired results. Program: #include <iostream.h> class ClassA { public: void display(void) { cout<<"ClassA\n"; } }; class ClassB : ClassA { public: void display() {cout<<"ClassB\n";} }; class ClassC : ClassB { public: void display(void) { cout<<"ClassC\n";

Page 115: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

115

} }; main() { ClassA *p,a; ClassB b; ClassC c; p=&a; p->display(); ((ClassB *)p)->display(); ((ClassC* )p)->display(); } Output:

ClassA ClassB ClassC

Virtual functions Late / Dynamic Binding : If the Inheritance relationship is defined as a logical "is-s" relationship, can we use a derived class in place where a base class is expected ? A pointer to the derived class can be used wherever a pointer to the base class is expected. It would not be sufficient to allow just this equality of pointer, member function calls (for example calcuate_interest ()) should also be made, so that depending on the actual instance the correct version of the function is called. This would avoid the use of a switch statement and also avoid storing the type of the object. C++ requires that the designer of the base class identify all such functions and qualify them with the keyword virtual. This is called as run-time binding., as at compile time, it may not be clear which function would actually be called. Some other Oriented Programming language make all functions run-time bound. C++ choose the center path to reduce inefficiencies caused by run-time binding. This is also called Late Binding. There is a discrepancy between treating an object as a member of the base class and treating it as a member of a derived class. We would often like a common interface provided by a base class, but different implementations of the methods created in derived class. If suppose we have two derived class D1 and D2 of a base class B, and all three of them had a method called display(). Further suppose an array of he base class that contained members of both the derived classes was being used. Then a call to display() must be resolved before the program executes. When the compiler

Page 116: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

116

generates a call to display(), for each element of the array of class B element, it generates a call to B::Display(), because that is the only function it knows in that context. Resolving the function call at compile time is called early or static binding. Thus even though the object is being accessed from the base class, the display() functions D1.display() or D2.display() should be called depending on which of the derived classes that particular object belong to. Resolving a function at run time is called late or Dynamic Binding. Static Binding or Early Binding is normal in most programming language, in particular procedural languages. With Static binding, the compiler and the linker directly define the fixed address of the code to be executed on every function call. With dynamic binding or late binding, the time to decide which of a list of addresses is the actual one. Only during the execution of the program some value will be used by run-time mechanism to determine the effective address among the several that are possible (one for every derived class). Properties of Virtual Functions : The following properties about virtual function should be noted:

1. Virtual functions called from within the member functions of base class would call the correct function at run-time.

2. Virtual functions called from within constructors would not call the expected

function. as the object of the derived class is not created when the constructor of the base class is being executed.

3. Virtual functions cannot be overloaded. This is very inconvenient.

The Overloading is not allowed for many reasons.

a) As overloading is defined over scopes, overloading of a virtual function would not mean matching of parameters across classes.

b) Allowing a feature like this, would require type information to be stored for the run time. Currently, even the linker does not have type information, overloading being achieved by name mangling.

c) C++ is intended to be a strictly typed language - meaning that all type mismatches would be pointed out by the compiler. Given that type resolution is required at tun time, type mismatch errors could occur at run time. This is undesirable for production quality software.

Polymorphism :

Page 117: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

117

Polymorphism means "having many forms". Function overloading and operator overloading are examples of a single entity and multiple forms. That's polymorphism. Polymorphism operates on two levels: Compile-time polymorphism and Run-time polymorphism. Function overloading and operator overloading exemplify compile-time polymorphism. run-time polymorphism stands on two basic features : virtual function and derived classes. Let us see virtual functions. Let us see an example of Polymorphism. Program; #include <iostream.h> class A { public: virtual void display (void) { cout<<"this is class A\n"; } }; class B: public A { public: void display (void) { cout<<"this is class B\n"; } }; class C : public B { public: void display (void) { cout<<"this is class C\n"; } }; main() { A *pa, a;

Page 118: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

118

B b; C c; pa=&a; pa->display(); pa=&b; pa->display(); pa=&c; pa->display(); } Here the class c does not have its own method display(). so who will it borrow it from? A or B? The answer lies in the output: this is class A this is class B this is class C Polymorphism functions through a process called Late binding. In the process of compiling a program, what you get is an .obj file, with the references to the various function. At the linking stage, these externals are resolved to get an exe file. This type of linking is referred to as early binding. As against early binding is late binding. The platform on which polymorphism rests. In this kind of binding process, the externals are resolved not at link-time, buy at run-time. It is only at run time that the decision about the function pointed to can be made. Without this facility polymorphism would have remained only a theory. Virtual Functions "Virtual Functions' are functions that ensure that the correct function is called for an object, regardless of the expression used to make the function call. Suppose a base class contains a function declared as virtual and a derived class defines the same function. The function from the derived class is invoked for objects of the derived class, even if it is called using a pointer or reference to the base class. The following example shows a base class that provides an implementation of the Print Balance functions: Program: #include<iostream.h> class Account { public: Account( double d ); // Constructor. virtual double GetBalance(); // Obtain balance. virtual void PrintBalance(); // Default impleemntation.

Page 119: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

119

private: double _balance; }; // Implementation of constructor for Account. Account::Account(double d) { _balance = d; } // Implementation of GetBalance for Account. double Account::GetBalance() { return _balance; } // Default implementation of PrintBalance. void Account::PrintBalance() { cerr<<"Error.Balance not available for base type." <<endl; }

Exercise

Explain inheritance and its advantages. Explain all the types of inheritance. Explain abstract classes. Explain virtual function. Explain polymorphism.

Explain Constructors & Destructors with inheritance.

Page 120: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

120

Chapter - 10 FILES

THE STREAM CLASS HIERARCHY A stream is a source or destination for a collection of characters or a flow of data. There are two kinds of streams:

Output streams, which allow you to write or store characters Input streams, which allow you to read or fetch characters

The input and output capabilities of C++ stem from the fact that each stream is associated with a particular class. For example, the input streams are associated with the istream class and the output streams are associated with the ostream class. Each class contains its own member data, and functions and definitions for dealing with the data in a particular kind of stream. The following is a list of features of the C++ stream classes:

They form a powerful set of classes that can be modified, extended, or expanded to incorporate user defined data types or classes.

They are fully buffered to reduce disk access. A buffer is a region in memory that temporarily stores data until it can be sent to its destination. Buffers are meant for both input as well as output. For output streams, it holds the data until it can be sent to its destination. For input streams, it reads ahead so that it reduces the physical input and output on the disk.

They encapsulate their internal working from the user. Thus, the programmer need not specify the type of data that is to be input or output; the stream class automatically determines it.

They offer a rich set of error-handling facilities. The figure below shows the hierarchy of the stream class library.

Page 121: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

121

The Stream Class Hierarchy The ios class is the virtual base class of the stream class hierarchy. It defines the basic format for input/output and error control procedures. The istream and ostream classes are derived from the class. The ios class contains a pointer to an object of class, streambuf. The streambuf class manages memory for the input and output buffers. The class, ios, has been defined in the header file, ios. The recently created C++ libraries that conform to the latest standard use the class, ios_base, and the older libraries use the class, ios. The istream (input stream) class uses data from a stream buffer. The object, cin, controls input from a stream buffer associated with the object, stdin, declared in the file, cstdio. The ostream (output stream) class is used to define the format in which data is displayed to the VDU (standard output device). The object, cout, is associated with the object, stdout, but the data used is from a stream buffer. The iostream (input and output stream) class is derived from istream and ostream classes through multiple inheritance. Therefore, it inherits both the input and output attributes. The header file, iostream, has the class definitions for istream, ostream, and iostream.

ios

fstream

iostream

istream ostream

ifstream ofstream

Page 122: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

122

C++ provides specific classes, which deal with user-defined stream. User-defined stream are in the form of files and are linked to a stream. A stream must be obtained before a file is opened. These streams are more powerful than the predefined iostreams. There arethree stream classes that provide file input/output capabilities. They are:

The ifstream class, derived from the istream class, and used for file input (reading).

The ofstream class, derived from the ostream class, and used for file output (writing).

The fstream class, derived from the iostream class, and used for both file input and output.

The definitions for these classes are in the header file, fstream. This file also includes iostream, so there is no need for you to explicitly include it. The classes defined fstream take care of all file input/output. File input and output is an extension of stream extraction and insertion. The open () Function Each file stream class has an open () member function which is used to open files. The following statements illustrate the same. ifstream Ifil; //creates an unopened input stream Ifil.open (“DATA.DAT”); //associates the stream to a file The close () Function Each file stream class also has a close () function which can be used to close a file explicitly. This is illustrated below: Ofstream Ofil; Ofil.open (“DATA.DAT”);

… … Ofil.close ();

Here the file, DATA.DAT, is closed. However, the object, Ofil, is still available in the memory, though it is not associated with any particular data file. This technique of closing files is useful when you want to use the same object to process any different files in a single program. OPEN MODE BITS

Page 123: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

123

The following table details the entire file opening modes: Mode Explanation App Starts reading or writing at the end of the file. Does not have

a meaning with input streams, it is used only for output streams.

In Open for reading Out Open for writing Ate Seek to the end of the file Trunk If the file exists, it is truncated, i.e. all data is erased before

writing/reading Reading from the file #include<iostream.h> #include<fstream.h> void main() { ofstream out; out.open("C:\\data.txt"); out<<"Hello\nWriting to the file"; out.close(); } The above example will create a file data.txt in C:/ and write the following line as shown below. Hello Writing to the file Writing from the file #include<iostream.h> #include<fstream.h> void main() { ifstream in; char ch; in.open("C:\\data.txt"); while(in) { in.get(ch); cout<<ch; } in.close();

Page 124: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

124

} Note: To check whether the file is found or not there is a function called bad(). Better way to read from the file #include<iostream.h> #include<fstream.h> int main() { ifstream in; char str[30]; in.open("C:\\data.txt"); if(in.bad()) { cout<<"\nError reading the file."; return 0; } while(!in.eof()) { in.getline(str,30,'/n'); cout<<str<<endl; } in.close(); } File Input and Output using Objects Here is an example of file output using an object of a user-defined class, Vehicle. #include<fstream.h> #include<string.h> // for strcpy () class Vehicle { public: int serialNo; char model[8]; int price; }; int main () { ofstream out ("C:\\obj.txt"); Vehicle car; car.serialNo = 55;

Page 125: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

125

strcpy (car.model, "Opel"); car.price = 9999; out<< car.serialNo << endl << car.model <<endl << car.price; return 0; } The above program creates a file, obj.txt, in C:/, and writes the contents of the object car to the file. The file can be opened using any editor. It contains the following: 55 Opel

9999 The following program illustrates the input of objects from a file. #include<fstream.h> class Vehicle { public: int serialNo; char model[8]; double price; }; int main () { ifstream in("C://obj.txt"); Vehicle car; in >> car.serialNo; in >> car.model; in >> car.price; cout << endl<< car.serialNo << endl << car.model << endl << car.price; return 0; } The output of the program would be:

55 Opel 9999

Reading & Writing in Binary format The read () Function

Page 126: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

126

Syntax

read(char*addr, int size)

The address of the array into which the file is to be read is addr. The array must be of the character type. Therefore, if any other type of address is passed as the first parameter, it has to be type cast to a character pointer. However, some C++ compilers support a void *. This means that any pointer type can be used as an argument, without type casting.

The number of bytes to read is size. The write () Function Syntax

write(char*addr, int size) FILE POINTERS The C++ input and output stream manages two integer values associated with a file. These are:

The get pointer, which specifies the location in the file where the next read operation will occur.

The put pointer, which specifies the location in the file where the next write operation will occur.

However, you may have to manipulate file pointers to read from and write to only a particular location in a file. The seekg () and tellg () functions help you to control the get pointer. The seekp () and tellp () functions do similar operations on the put pointer. In other words, these four functions allows you to access the file in a non-sequential or random mode. The tellg () and tellp () functions can be used to find the current position of the get and put file pointers respectively, in a file. The seekg () member function takes two arguments:

The number of bytes to move The reference in the file from where the pointer has to be repositioned

Page 127: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

127

Example ifstream iFil; iFil.seekg (10, ios::beg); means, “position the get pointer 10 bytes from the beginning of the file” The first argument is an integer that specifies the number of byte positions (also called offset). The second argument is the reference point. There are three reference points defined in the ios class:

ios::beg – Beginning of the file

ios::cur – Current position of the file pointer ios::end – End of the file

A negative value can also be specified for the first argument. For example, the following statement moves the file pointer 20 bytes in the reverse direction from the end of the file. iFil.seekg (-20, ios::end); If the seekg () function is used with only one argument, the ios::beg reference point is assumed. For example in the statement: iFil.seekg (16); ios::beg will be the reference point and hence the get pointer will be positioned 16 bytes from the beginning of the file. The tellg () member function does not take any arguments. It returns the current byte position of the get pointer relative to the beginning of the file. For example the statement: int iPosition=iFil.tellg (); will result in the variable, iPosition, having the value of the current position of the get pointer. The seekp () and tell0 () member functions are identical to the above two functions, but they are identified with the put pointer. The seekg () and tellg () member functions are defined in the istream class. The seekp () and tellp () member functions are defined in the ostream class.

Page 128: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

128

Program for reading and writing data of customers #include<iostream.h> #include<fstream.h> #include<conio.h> class customer { private: char name[25]; char city[25]; char phoneno[11]; float bal; public: void print() { cout<<endl<<"Name:"<<name; cout<<endl<<"City:"<<city; cout<<endl<<"Phone Number:"<<phoneno; cout<<endl<<"Balance:"<<bal; } void get() { cout<<endl<<"Name:"; cin>>name; cin.ignore(); //clears the buffer cout<<endl<<"City:"; cin>>city; cin.ignore(); //clears the buffer cout<<endl<<"Phone Number:"; cin>>phoneno; cout<<endl<<"Balance:"; cin>>bal; } }; void main() { customer object; fstream file; char reply='y'; file.open("customer.dat",ios::out|ios::app); while(reply=='y'||reply=='Y') {

Page 129: Chapter - 1saintangelos.com/studentdesk/Download/Cpp.pdfC++ St. Angelo’s Computers Education 1 Chapter - 1 OOPS INTRODUCTION C++ PROGRAMMING Object Oriented Programming: The object-oriented

C++ St. Angelo’s Computers Education

129

cout<<"\nEnter customer details"<<endl; object.get(); file.write((char*)&object,sizeof(object)); cout<<"\nDo you want to continue(y/n):"; cin>>reply; } file.close(); file.open("customer.dat",ios::in); file.read((char*)&object,sizeof(object)); while(!file.eof()) { object.print(); file.read((char*)&object,sizeof(object)); } file.close(); } Exercise

Explain stream class hierarchy. Explain file input/output using objects. Explain reading and writing files in binary format. Explain all the file manipulators.