Object Oriented Programming using C++ - OOPS concepts using C++ programming language
PreethaV16
57 views
178 slides
Jun 16, 2024
Slide 1 of 257
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
About This Presentation
This ppt includes detailed description about Object Oriented Programming using C++.
Size: 2.76 MB
Language: en
Added: Jun 16, 2024
Slides: 178 pages
Slide Content
20CSG01 - OBJECT ORIENTED PROGRAMMING USING C++ 1 SRI RAMAKRISHNA INSTITUTE OF TECHNOLOGY, COIMBATORE-10 (An Autonomous Institution) Approved by AICTE, New Delhi – Affiliated to Anna University, Chennai) (Accredited by NAAC with ‘A’ Grade and All UG Engineering Programmes are Accredited by NBA) Department of Computer Science and Engineering Object Oriented Programming using C++ - Preetha V AP/CSE
Outline Fundamentals of OOP and C++ Structural versus object-oriented Programming - Elements of object oriented programming- benefits of OOP – Structure of C++ program - Variables - Tokens - Keywords – Identifiers -Type modifiers - Type casting - Input and Output - Data Types and Expressions - Operators - Flow of control - Arrays, Strings and Pointers. Classes and Objects Classes and Objects - Class specification: Class Members, Access Specifier , Scope resolution operator- Class Instantiation - Accessing class members- Passing and returning objects - Array of objects – Constructors: Parameterized constructors - Default arguments – Copy Constructor - Constructor overloading, Destructors - new, delete operators - “this” pointer - Friend classes and friend functions. Object Oriented Programming using C++ - Preetha V AP/CSE 2
Programming Languages Programming languages allow programmers to code software. The three major families of languages are: Machine languages Assembly languages High-Level languages Object Oriented Programming using C++ - Preetha V AP/CSE 3
Machine Languages Comprised of 1s and 0s The “native” language of a computer Difficult to program – one misplaced 1 or 0 will cause the program to fail. Example of code: 1110100010101 111010101110 10111010110100 10100011110111 Object Oriented Programming using C++ - Preetha V AP/CSE 4
Assembly Languages Assembly languages are a step towards easier programming. Assembly languages are comprised of a set of elemental commands which are tied to a specific processor. Assembly language code needs to be translated to machine language before the computer processes it. Example: ADD 1001010, 1011010 Object Oriented Programming using C++ - Preetha V AP/CSE 5
High-Level Languages High-level languages represent a giant leap towards easier programming. The syntax of HL languages is similar to English. Historically, we divide HL languages into two groups: Procedural languages Object-Oriented languages (OOP) Object Oriented Programming using C++ - Preetha V AP/CSE 6
Procedural Languages Early high-level languages are typically called procedural languages. Procedural languages are characterized by sequential sets of linear commands. The focus of such languages is on structure . Examples include C, COBOL, Fortran, LISP, Perl, HTML, VBScript Object Oriented Programming using C++ - Preetha V AP/CSE 7
TYPICAL STRUCTURE OF POP Object Oriented Programming using C++ - Preetha V AP/CSE 8
Relationship of Data And Functions of POP Object Oriented Programming using C++ - Preetha V AP/CSE 9
Object-Oriented Languages Most object-oriented languages are high-level languages. The focus of OOP languages is not on structure, but on modeling data . Programmers code using “blueprints” of data models called classes . Examples of OOP languages include C++, Visual Basic.NET and Java . Object Oriented Programming using C++ - Preetha V AP/CSE 10
Object Oriented Programming using C++ - Preetha V AP/CSE 11
INTRODUCTION T Bells LAB early in 1980’s by BJARNE STROUSTRUP. STROUSTRUP added some features to his favorite language Simula 67. (Earliest OOP). STROUSTRUP called “ C with Classes ”. C++ ( C Plus Plus) is named by Rick Masitti. Object Oriented Programming using C++ - Preetha V AP/CSE 12
Born December 30, 1950 ) (age 60) Aarhus, Denmark Occupation College of Engineering Chair in Computer Science Professor, Texas A&M University USA Known for The creation of C++ BJARNE STROUSTRUP Object Oriented Programming using C++ - Preetha V AP/CSE 13
Basic concepts of OOP Object based programming is a newer paradigm that implements some features of object oriented programming but not all. In object based programming, data and its associated meaningful functions are enclosed in one single entity a class. Classes enforce information hiding and abstraction thereby separating the implementation details and the uses interface . Object Oriented Programming using C++ - Preetha V AP/CSE 14
Contd.. Object - Objects have states and behaviors. Example: A Student has states - color, name, as well as behaviors - reading, writing, eating. An object is an instance of a class. Class - A class can be defined as a template/blueprint that describes the behaviors/states that object of its type support. Methods/Member functions - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed. Instance Variables/Data Members - Each object has its unique set of instance variables. An object's state is created by the values assigned to these instance variables. Object Oriented Programming using C++ - Preetha V AP/CSE 15
Basic concepts of OOP These general concepts of OOP are given below: Data Abstraction Data Encapsulation Modularity Inheritance Polymorphism Object Oriented Programming using C++ - Preetha V AP/CSE 16
Data Abstraction Abstraction refers to the act of representing essential features without including the background details or explanations. Since the classes use the concept of data abstraction , they are known as ADT (Abstract Data Types). Object Oriented Programming using C++ - Preetha V AP/CSE 17
Data Encapsulation The wrapping up of data and operations / functions (that operate on the data) into a single unit (called class) is known as Encapsulation . The data is not accessible to the outside world, and only those functions which are wrapped in the class can access it. These functions provide the interface between the object’s data and the program. The insulation of the data from direct access by the program is called data hiding or information hiding. Object Oriented Programming using C++ - Preetha V AP/CSE 18
Data Member Functions Data Member Functions Data Member Functions Object Object Object Object Oriented Programming using C++ - Preetha V AP/CSE 19
What is a Modularity ? Modularity is the property of a system that has been decomposed into a set of cohesive and loosely coupled modules. Object Oriented Programming using C++ - Preetha V AP/CSE 20
Modularity The act of partitioning a program into individual components is called modularity. The justification for partitioning a program is that it reduces its complexity to some degree and it creates a number of well-defined, documented boundaries within the program Object Oriented Programming using C++ - Preetha V AP/CSE 21
Inheritance Inheritance is the capability of one class of things to inherit capabilities or properties from another class. Inheritance is the process by which objects of one class acquire the properties of objects of another class. It supports the concept of hierarchical classification . In OOP, the concept of inheritance provides the idea of reusability . Object Oriented Programming using C++ - Preetha V AP/CSE 22
Vehicles Automobiles (Motor driven) Pulled Vehicles Car Bus Cart Rickshaw Property Inheritance Object Oriented Programming using C++ - Preetha V AP/CSE 23
Polymorphism Polymorphism is the ability for a message or data to be processed in more than one form. The process of making an operator to exhibit different behaviours in different instances is known as operator overloading . Using a single function name to perform different types of tasks is known as function overloading. Object Oriented Programming using C++ - Preetha V AP/CSE 24
Circle Area ( circle ) Rectangle Area ( rectangle ) Shape Area Triangle Area ( triangle ) Polymorphism Object Oriented Programming using C++ - Preetha V AP/CSE 25
Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding(also known as late binding or run-time binding ) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance. Object Oriented Programming using C++ - Preetha V AP/CSE 26
Message Passing Message passing involves specifying the name of the object,the name of the function(message) and the information to be sent. Object Oriented Programming using C++ - Preetha V AP/CSE 27
Benefits of oops OOP offers several benefits to the program designer and the user. Object-orientation contributes to the solutions of many problem associated with the development and quality of software products. The new technology promises greater programmer productivity, better quality of software and lesser maintenance cost. Object Oriented Programming using C++ - Preetha V AP/CSE 28
CONTD.. The principal advantages Through inheritance, we can eliminate redundant code and extend the use of existing classes. We can built programs from standard working modules that communicate with one another rather than, having to start writing the code from scratch. This leads to saving of development time and higher productivity. The principle of data hiding helps the programmers to built secure program that can’t be invaded by code in other parts of the program. It is possible to have multiple objects to coexist without any interference. It is possible to map objects in the problem domain to those objects in the program Object Oriented Programming using C++ - Preetha V AP/CSE 29
ADVANTAGES of OOP Re-use of code. Ease of comprehension. Ease of fabrication and maintenance. Easy redesign and extension. Object Oriented Programming using C++ - Preetha V AP/CSE 30
DISADVANTAGES of OOP With OOP, classes tend be overly generalized. The relations among classes become artificial at times. The OOP programs’ design is tricky. Also one need to do proper planning and proper design for OOP programming. To program with OOP, programmer need proper skills such as design skills, programming skills, thinking in terms of objects etc . Object Oriented Programming using C++ - Preetha V AP/CSE 31
C++ CHARACTER SET Letters: - A-Z, a-z Digits :- 0 to 9 Special Symbols :- space + - / ( ) [ ] = ! = < > , ‘ “ $ # ; : ? & White Spaces :- Blank Space , Horizontal Tab, Vertical tab, Carriage Return. Other Characters :- C++ can process any of the 256 ASCII Characters as data or as literal . Object Oriented Programming using C++ - Preetha V AP/CSE 32
TOKENS The Smallest individual unit in a program is known as Token. Lexical Unit is the another name given to Token. C++ has following Tokens Keywords Identifiers Literals or Constants Punctuators Operators Object Oriented Programming using C++ - Preetha V AP/CSE 33
KEY WORDS Key words are the words that convey special meaning to the compiler. Key words are also called as Reserved words meaning their meaning is reserved in C++. Some of Key words are, float int auto extern double if else char case do while goto … etc Added by ANSI C++ bool true false export mutable typeid typename using Object Oriented Programming using C++ - Preetha V AP/CSE 34
IDENTIFIERS Identifier refers to the name of variables, functions, arrays, classes, etc. created by the programmer. Identifier is an arbitrary long sequence of letters and digits. The first character must be letter. The underscore ( _ ) counts as letter. Upper and Lower case letters are different. All characters are significant. Object Oriented Programming using C++ - Preetha V AP/CSE 35
EXAMPLES OF IDENTIFIERS C++ is a Case Sensitive Language as it treats upper case letters and lower case letters differently. Some Valid identifiers, Myfile DATE9_7_8 z3t9x3 MYFILE _DS _FXR Some Invalid identifiers, DATA-REC 28dre break Object Oriented Programming using C++ - Preetha V AP/CSE 36
LITERALS Literals often referred to as constants. Constants refers to fixed values that do not change during the execution of a program. These are the data items that never change their value during the program run. Object Oriented Programming using C++ - Preetha V AP/CSE 37
TYPES OF C++ LITERALS INTEGER – CONSTANT CHARACTER – CONSTANT FLOATING – CONSTANT STRING – LITERAL Object Oriented Programming using C++ - Preetha V AP/CSE 38
INTEGER CONSTANT These are the whole numbers without any fractional part. An integer constant must have at least one digit and must not contain fractional part. It may contain + or - Sign. A number with no sign is assumed as positive. Commas can not appear in integer constant. Object Oriented Programming using C++ - Preetha V AP/CSE 39
TYPES OF INTEGER CONSTANTS Decimal Integer Constants Octal Integer Constants Hexadecimal Constants Object Oriented Programming using C++ - Preetha V AP/CSE 40
DECIMAL INTEGER CONSTANT An integer constant consisting of sequence of digits is taken to be decimal integer constant unless it begins with 0. For instance 1234,56,+86,-56,-89,-22 are decimal integer constant. Object Oriented Programming using C++ - Preetha V AP/CSE 41
OCTAL INTEGER CONSANT A sequence of digits starting with 0(digit Zero) is taken to be an octal integer constant. for instance Decimal 8 is written as 010 as octal integer 8 10 =10 8 Decimal 12 is written as 12 10 = 14 8 Object Oriented Programming using C++ - Preetha V AP/CSE 42
CHARACTER CONSTANT A character constant is one character enclosed within single quotes Valid constants ‘a’ ‘z’ ‘k’ Invalid Constants a z k In c++ character constant must have single character and must be enclosed in single quotes. Object Oriented Programming using C++ - Preetha V AP/CSE 43
NONGRAPHIC CHARACTERS Nongraphic character constants are those characters that can not be typed directly from the keyboard. e.g backspace, tab, carriage return C++ Allows programmers to have certain nongraphic characters. Object Oriented Programming using C++ - Preetha V AP/CSE 44
ESCAPE SEQUENCES Escape sequences are nongraphic character constants these are also called as non printing characters. These nongraphic characters are represented by means of escape sequence and is represented by a backslash ( \ ) followed by a one or more character. Object Oriented Programming using C++ - Preetha V AP/CSE 45
ESCAPE SEQUCENCE IN C++ Escape Sequence Non Graphic Character \a Bell \b Back Space \f Form Feed \n New Line \r Carriage Return \t Horizontal Tab \v Vertical Tab \’ Single Quote \” Double Quote \? Question Mark \on Octal Number ( On represents the number in octal) \ xHn Hexadecimal number \0 Null Object Oriented Programming using C++ - Preetha V AP/CSE 46
NOTE THESE ESCAPE SQUENCES ARE USED IN OUTPUT STATEMENT COUT FOR EX: cout<<“\n\t Wel Come”; // Right statement cin >>”\n\t”>>n; //Wrong statement Do not use in cin statements Object Oriented Programming using C++ - Preetha V AP/CSE 47
FLOATING CONSTANTS Floating constants are also called as Real constants. These may be written in one of two of forms called fractional form or exponent form. A real constant in fractional form must have one digit before a decimal point and at least one digit after the decimal point. It may also have either +ve or –ve sign preceding it. A real constant with no sign is assumed to be positive. Object Oriented Programming using C++ - Preetha V AP/CSE 48
EXAMPLES OF REAL CONSTANTS The following are the valid real constants in fractional form. 2.0 17.5 -89.9 -0.000732 The following are the invalid real constants in fractional 7 7. 24.34.32 12,45,344.09 Object Oriented Programming using C++ - Preetha V AP/CSE 49
REAL CONSTANTS IN EXPONENT FORM A Real constant in exponent form has two parts 1. Mantissa 2. Exponent Mantissa must be either an integer or proper real constant. The mantissa is followed by letter E or e and the exponent must be an integer. Object Oriented Programming using C++ - Preetha V AP/CSE 50
EXAMPLE OF REAL CONSTANTS The floating point number 5.8 can be written as, 0.58 x 10 1 =0.58E01 or 0.58e01, here E01 or e01 represents 10 1 0.58 E01 Mantissa part Exponent part Valid Real Constants : 123E03, 0.76e02, -0.12e-2 Invalid Real Constants: 172.E03, 1.2E,0.4E2.3 Object Oriented Programming using C++ - Preetha V AP/CSE 51
STRING LITERAL A String Literal is a sequence of characters surrounded by double quotes A Multi character constants are treated as string literals. For Example: “ abc ” in the memory this string is represented as “ abc \0” i.e along with the terminating character (Slash Zero). String is an array of character. Object Oriented Programming using C++ - Preetha V AP/CSE 52
PUNCTUATORS Punctuators are also called as separators The Followings are used as punctuators Brackets [ ] Parantheses ( ) Braces { } Comma , Semicolon ; Colon : Asterisk * Ellipsis … Equal Sign = Pound Sign # Object Oriented Programming using C++ - Preetha V AP/CSE 53
OPERATORS Operators are the foundation of any programming language. Operators allows us to perform different kinds of operations on operands. Operators are tokens that triggers some computation when applied to a variable and other objects in an function. Object Oriented Programming using C++ - Preetha V AP/CSE 54
UNARY OPERATORS Unary Operators are those operators they act upon one operand. OR Operators that require one operator to operate upon. & Address Operator * Indirection Operator + Unary Plus - Unary Minus ~ Bitwise Compliment ++ Increment Operator -- Decrement Operator Object Oriented Programming using C++ - Preetha V AP/CSE 55
BINARY OPERATORS Binary Operators are those operators that require two operands to operate upon. Arithmetic Operators + Addition - Subtraction * Multiplication / Division % Remainder or Modulus Object Oriented Programming using C++ - Preetha V AP/CSE 56
SHIFT OPERATORS << (Shift Left) >> (Shift Right) For More information you will study in future chapters. Object Oriented Programming using C++ - Preetha V AP/CSE 57
LOGICAL OPERATORS && Logical AND || Logical OR ! Logical Negation Object Oriented Programming using C++ - Preetha V AP/CSE 58
ASSIGNMENT OPERATORS The assignment operator is used to store the constants, variables, and result of an expression and return value of a function from right side into variable placed in left side. = Assignment Operator When same variable is used in both left and right side of an arithmetic expression, we can use the shortcut assignment operators . The operators are : +=, – =, *=, /=, %= *= Assign Product a*=b------------ a=a*b /= Assign Quotient %= Assign Remainder += Assign Sum -= Assign Minus Object Oriented Programming using C++ - Preetha V AP/CSE 59
Relational Operator < Less than > Greater than <= Less than equal to >= Greater than equal to == Equal to != Not equal to Object Oriented Programming using C++ - Preetha V AP/CSE 60
Other Operators Conditional operators: The ?: are conditional operators. They do the job done by if..else control structure. Syntax : expression1 ? expression2 : expression3; Ex : big = (a>b) ? a : b; Sizeof and Comma operators : The sizeof operator returns the memory size occupied by an operand in terms of bytes. Ex : a = sizeof ( int ); The comma operator (,) adjoins several expressions. Ex : x = (y = 3, y + 1); Object Oriented Programming using C++ - Preetha V AP/CSE 61
Operators in C++ C++ introduces some new operators. They are : << insertion operator (or output operator) >> extraction operator (or input operator) :: Scope resolution operator ::* pointer-to-member declarator ->* pointer-to-member operator .* pointer-to-member operator delete memory release operator endl line feed operator new memory allocation operator setw field width operator Object Oriented Programming using C++ - Preetha V AP/CSE 62
Basic Data types Object Oriented Programming using C++ - Preetha V AP/CSE 64
Built-in- data type Primary (Fundamental) data types in C/C++ programming includes the 4 most basic data types, that is: int : It is responsible for storing integers. The memory it occupies depends on the compiler (32 or 64 bit). In general, int data type occupies 4 bytes of memory when working with a 32-bit compiler. float : It is responsible for storing fractions or digits up to 7 decimal places. It is usually referred to as a single-precision floating-point type. It occupies 4 bytes of memory char : It can be used to store a set of all characters which may include alphabets, numbers and special characters. It occupies 1 byte of memory being the smallest addressable unit of a machine containing a fundamental character set. double : It is responsible for storing fractions or digits up to 15-16 decimal places. It is usually referred to as a double-precision floating-point type. It occupies 8 bytes of memory void (Null) data type: It indicates zero or no return value. It is generally used to assign the null value while declaring a function. Object Oriented Programming using C++ - Preetha V AP/CSE 65
Built-in- data type In C++, in addition to the primary data types available in C, there are few more data types available in the C++ programming language.They are: bool : It refers to a boolean /logical value. It can either be true or false. wchar_t : It refers to a wide character whose size is either 2 or 4 bytes. It is similar to the char data type but the only difference is the space occupied in the computer memory. string : Instead of declaring an array of characters to enter a string data type, C++ gives you the provision to declare the “string” data type. Object Oriented Programming using C++ - Preetha V AP/CSE 66
Derived Data Types Secondary (Derived) Data Types in C and C++ As the name itself suggests, they are derived from the fundamental data types in the form of a group to collect a cluster of data used as a single unit. These include: Arrays : A collection of data items of similar data types, which is accessed using a common name. The basic syntax of declaring an array is: return_type array_name [size]; For instance: float marks[5]; Pointers: Pointers in C/C++ are basically variables that are used to store the memory address of another variable. Functions : It is a group of statements that are written to perform a specific task. Functions are either user-defined or built-in library functions. Object Oriented Programming using C++ - Preetha V AP/CSE 67
User-defined Data Types User-defined Data Types in C and C++ Structures – It is a user-defined data type in which a collection of different data types can be made and accessed through an object. Union – A special kind of data type which gives us the provision to store different data types in the same memory location. Class - C++ also permits us to define another user-defined data type known as class which can be used, just like any other basic data type, to declare variables. The class variables are known as objects. Enumeration – It refers to the arithmetic data types used to define variables to specify only certain discrete integer values throughout the entire program. Object Oriented Programming using C++ - Preetha V AP/CSE 68
Reference variables in C++ When a variable is declared as reference, it becomes an alternative name for an existing variable. A variable can be declared as reference by putting ‘&’ in the declaration. The reference variable can be created as follows: data-type & reference-name=variable-name; C++ assigns additional meaning to the symbol &. Here, & is not an address operator. Object Oriented Programming using C++ - Preetha V AP/CSE 69
Object Oriented Programming using C++ - Preetha V AP/CSE 70
#include<iostream> using namespace std ; //Using namespace std , tells the compiler to use standard namespace. Namespace collects identifiers used for class, object and variables. int main() { int x = 10; // ref is a reference to x. int &ref = x; // Value of x is now changed to 20 ref = 20; cout << "x = " << x << endl ; // Value of x is now changed to 30 x = 30; cout << "ref = " << ref << endl ; return 0; } Output: x = 20 ref = 30 Object Oriented Programming using C++ - Preetha V AP/CSE 71
Type modifiers Modifiers basically alter the function of a data type and make it more specific by the inclusion of additional provisions. C++ allows us to use some modifiers for int, char and double types signed unsigned long Short Signed : It is used to store zero, positive or negative values.( signed variable stores the signed value in the allocated memory ) Unsigned : It can store only zero or positive values.( unsigned variable does not store signed value ) Long : It is used to store large integer numbers. The size of the long type is 8 bytes. Short : It is used to store small integer numbers. Its size is of 2 Bytes. short modifier makes a type to use less number of bytes and it reduces the range of values for that type. Object Oriented Programming using C++ - Preetha V AP/CSE 72
Type modifiers long and short modify the maximum and minimum values that a data type will hold. A plain int must have a minimum size of short . Size hierarchy : short int < int < long int Size hierarchy for floating point numbers is : float < double < long double long float is not a legal type and there are no short floating point numbers. Signed types includes both positive and negative numbers. Unsigned , numbers are always without any sign, that is always positive. Object Oriented Programming using C++ - Preetha V AP/CSE 73
Type modifiers The modifiers signed, unsigned, long, and short can be applied to integer base types. In addition, signed and unsigned can be applied to char, and long can be applied to double. The modifiers signed and unsigned can also be used as prefix to long or short modifiers. For example, unsigned long int . C++ allows a shorthand notation for declaring unsigned, short, or long integers. You can simply use the word unsigned, short, or long, without int . It automatically implies int . For example, the following two statements both declare unsigned integer variables. unsigned x; unsigned int y; Object Oriented Programming using C++ - Preetha V AP/CSE 74
Type modifiers Data Type / Size(in bytes) Range short int / 2 -32,768 to 32,767 unsigned short int / 2 0 to 65,535 unsigned int / 4 0 to 4,294,967,295 int / 4 -2,147,483,648 to 2,147,483,647 long int / 4 -2,147,483,648 to 2,147,483,647 unsigned long int / 4 0 to 4,294,967,295 signed char / 1 -128 to 127 unsigned char / 1 0 to 255 float / 4 double / 8 long double / 12 wchar_t / 2 or 4 1 wide character Object Oriented Programming using C++ - Preetha V AP/CSE 75
Type casting Converting an expression of a given type into another type is known as type-casting . Implicit conversion Implicit conversions do not require any operator. They are automatically performed when a value is copied to a compatible type. Eg : short a=2000; int b; b=a; Here, the value of a has been promoted from short to int and we have not had to specify any type-casting operator . This is known as a standard conversion. Standard conversions affect fundamental data types, and allow conversions such as the conversions between numerical types (short to int , int to float, double to int...), to or from bool, and some pointer conversions. Some of these conversions may imply a loss of precision , which the compiler can signal with a warning. This warning can be avoided with an explicit conversion. Object Oriented Programming using C++ - Preetha V AP/CSE 76
Type casting Explicit conversion Eg : short a=2000; int b; b=(int) a; b= int (a); Two notations for explicit type conversion: (1) Functional notation (2) C-like casting notation Object Oriented Programming using C++ - Preetha V AP/CSE 77
Inbuilt Typecasting Functions in C/C++ There are 5 basic types of inbuilt typecast functions in C/C++ : atof (): We use it to convert string data type into the float data type. atoi (): We use it to convert string data type into the int data type . atol (): We use it to convert string data type into the long data type . itoa (): We use it to convert int data type into the string data type . ltoa (): We use it to convert long data type into the string data type . Object Oriented Programming using C++ - Preetha V AP/CSE 78
Control Statements Control statements are elements in the source code that control the flow of program execution. They include blocks using { and } brackets, loops using for, while and do while, and decision-making using if and switch. There are two types of control statements: conditional and unconditional . Object Oriented Programming using C++ - Preetha V AP/CSE 79
Control Statements Conditional statements are executed when one or more conditions are satisfied . The most common of these conditional statements is the if statement . C++ uses many other conditional statements including: if-else : An if-else statement operates on an either/or basis . One statement is executed if the condition is true; another is executed if the condition is false. if-else if-else : This statement chooses one of the statements available depending on the condition. If no conditions are true, the else statement at the end is executed. while : While repeats a statement as long as a given statement is true. do while : A do while statement is similar to a while statement with the addition that the condition is checked at the end. for : A for statement repeats a statement as long as the condition is satisfied. Object Oriented Programming using C++ - Preetha V AP/CSE 80
Control Statements Unconditional control statements do not need to satisfy any condition . They immediately move control from one part of the program to another part. Unconditional statements in C++ include: goto : A goto statement directs control to another part of the program.The goto statement is used for transferring the control of a program to a given label. The syntax of goto statement looks like this: goto label_name ; break : A break statement terminates a loop (a repeated structure) continue : Continue statement is used inside loops. Whenever a continue statement is encountered inside a loop, control directly jumps to the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body for the current iteration. Object Oriented Programming using C++ - Preetha V AP/CSE 81
Control Statements If statement Syntax: if(condition){ //code to be executed } If else statement Syntax: if(condition){ //code if condition is true }else{ //code if condition is false } Object Oriented Programming using C++ - Preetha V AP/CSE 82
Nested if statement if(condition) { //code to be executed } else if(condition) {//code to be executed } else if(condition) { //code to be executed } Else { //code to be executed } Object Oriented Programming using C++ - Preetha V AP/CSE 83
Switch Statements syntax switch (n) { case 1: // code to be executed if n = 1; break; case 2: // code to be executed if n = 2; break; default: // code to be executed if n doesn't match any cases } Object Oriented Programming using C++ - Preetha V AP/CSE 84
Input and output statements Input Stream: If the direction of flow of bytes is from device(for example: Keyboard) to the main memory then this process is called input. Output Stream: If the direction of flow of bytes is opposite, i.e. from main memory to device( display screen ) then this process is called output. Object Oriented Programming using C++ - Preetha V AP/CSE 85
Header files available in C++ for Input / Output operation iostream : iostream stands for standard input output stream. This header file contains definitions to objects like cin, cout etc. iomanip : iomanip stands for input output manipulators. The methods declared in this files are used for manipulating streams. This file contains definitions of setw, setprecision etc. fstream : This header file mainly describes the file stream. This header file is used to handle the data being read from a file as input or data being written into the file as output. Object Oriented Programming using C++ - Preetha V AP/CSE 86
Accessing Public Data Members class Student { public: int rollno ; string name; }; int main() { Student A; Student B; A.rollno =1; A.name="Adam"; B.rollno =2; B.name="Bella"; cout <<"Name and Roll no of A is :"<< A.name << A.rollno ; cout <<"Name and Roll no of B is :"<< B.name << B.rollno ; } Object Oriented Programming using C++ - Preetha V AP/CSE 87
PREDEFINED STREAMS IN I/O LIBRARY At the lowest level files are implemented as streams of bytes, then What is STREAM? A Stream is simply a sequence of bytes. Input and output operations are supported by the istream (input stream) and ostream (output stream) classes. Object Oriented Programming using C++ - Preetha V AP/CSE 88
PREDEFINED STREAMS IN I/O LIBRARY The ostream output operation, referred to as insertion and is performed by insertion operator << The istream input operation, referred to as extraction and is performed by extraction operator >> Object Oriented Programming using C++ - Preetha V AP/CSE 89
EXTRACTION AND INSERTION SYMBOLS extraction operator Symbol is, >> insertion operator symbol is, << Object Oriented Programming using C++ - Preetha V AP/CSE 90
cin and cout statements cin (pronounced as see-in) stands for console input. cout (pronounced as see-out) stands for console output. Object Oriented Programming using C++ - Preetha V AP/CSE 91
SYNTAX OF cin STATEMENT The general format or the syntax of cin statement is, cin >> variablename ; Or cin >>variablename1>>variablename2>>variable name3………>> variablename n ; for example if four variables are to be input form the keyboard then, cin >>a>>b>>c>>d; Or the same statement can be written as follows, cin >>a; cin >>b; cin >>c; cin >>d; Object Oriented Programming using C++ - Preetha V AP/CSE 92
SYNTAX OF cout STATEMENT The general format or the syntax of cout statement is, cout<< variablename ; Or cout<<variablename1<<variablename2<<variable name3………<< variablename n ; for example if four variables are to be input form the keyboard then, cout<<a <<b <<c <<d; Or the same statement can be written as follows, cout<<a; cout<<b; cout<<c; cout<<d; Object Oriented Programming using C++ - Preetha V AP/CSE 93
cout STATEMENT Another way of writing cout statement is, cout<<string<< variablename ; where, String is a sequence of characters enclosed within a double quotation. Variable name is the value of variable which is to be printed after the message(string) Object Oriented Programming using C++ - Preetha V AP/CSE 94
cout STATEMENT totalamt ;=6700; cout<<“The Total Amount is = “<< totalamt ; Here, in this example The Total Amount is= is the string And the totalamt is the variable name, the value of the total is printed Out put of this statement is as follows The total Amount is = 6700 Object Oriented Programming using C++ - Preetha V AP/CSE 95
cout STATEMENT As studied escape sequences are used in out put (cout) statements cout<<“\n\ tBasic Pay=“<<basic<<“\n\t DA=“<<da<<“\n\t HRA = “<< hra <<“\n\t Gross Salary = “<< gs ; output of the above statement is, Basic Pay=5900 DA=40 HRA =30 Gross Salary = 10030 Object Oriented Programming using C++ - Preetha V AP/CSE 96
COMMENTS The comments are the non executable statements . When ever compiler identifies this is comment then it ignores . There are two types of comments in C++ Single Line Comment (//) Multi Line Comment (starts with /* and ends with */) Object Oriented Programming using C++ - Preetha V AP/CSE 97
COMMENTS The comments are the non executable statements. When ever compiler identifies this is comment then it ignores. Single Line Comment Example // My First C++ Program This is the comment. All lines beginning with // are the comments in the program. Starting with /* and ended with */ is used for multi line comments Multi Line Comment Example /* Write a CPP Program that calculates the sum and average of three numbers*/ Object Oriented Programming using C++ - Preetha V AP/CSE 98
I/O OPERATORS Input coming from the user’s terminal referred to as standard input is tied to the predefined iostream cin output directed to the user’s terminal, referred to as standard output, is tied to the predefined iostream cout . Object Oriented Programming using C++ - Preetha V AP/CSE 99
OUTPUT OPERATOR “<<’’ The output operator (“<<’’) (“put to’’), also called as stream insertion operator is used to direct a value to the standard output device. For example cout<<“The Sum of 5 + 2 = “; cout<< 5 + 2 ; The statement will produce following output The Sum of 5 + 2 = 7 Object Oriented Programming using C++ - Preetha V AP/CSE 100
OUTPUT OPERATOR << Now observe the output of following statement. cout<< “The Sum of 5 + 2 is “; cout<< 5 + 2; cout<<“\n”; cout<<“The Result pf 8 – 2 is“; cout<<8 – 2 ; The Output of abve set of statements will be as follows, The Sum of 5 + 2 is 7 The Result pf 8 – 2 is 6 Object Oriented Programming using C++ - Preetha V AP/CSE 101
OUTPUT OPERATOR << The same statements can be written by using single cout statement cout<< “The Sum of 5 + 2 is<< 5 + 2<<“\n”<<“The Result pf 8 – 2 is“<<8 – 2 ; The Output will be same but code is reduced. The Sum of 5 + 2 is 7 The Result pf 8 – 2 is 6 Note: Stream insertion operator >> signifies that insert the value that follows in to the stream named cout. Object Oriented Programming using C++ - Preetha V AP/CSE 102
/* Write a C ++ Program that prints the sum of two values */ #include < iostream.h > // for I/O Operation #include< conio.h > // for clrscr () and getch () functions . int main() { clrscr () ; int value1, value2, sum ; cout << “Enter First Value:”; cin >>value1; cout<<“Enter Second Value:”; cin >>value2; Object Oriented Programming using C++ - Preetha V AP/CSE 103
Program contd.. sum=value1+value2; cout<<“The Sum of two given values is : “; cout<<sum; return 0; } Definition: Variable refers to a storage area whose contents can vary during processing. In this example sum , value1 , valu2 are the variables. NOTE: The Stream extraction operator >>, signifies “extract the next value” from the stream named cin and assign it to the next named variable Object Oriented Programming using C++ - Preetha V AP/CSE 104
OUTPUT OF PROGRAM The output produced by the program is as follows, Enter the First value: 6 Enter the Second value : 7 The Sum of the given value is : 13 Object Oriented Programming using C++ - Preetha V AP/CSE 105
CASCADING I/O OPERATOR The Multiple use of input or output operators (“>>” or “>>”) in one statement is called cascading of I/O operators. For Example OUTPUT OPERATOR cout<<“The sum of “; cout<<value1; cout<< “and “; cout<<value2; cout<<“ is “; cout<<value1+value2; This can be using cascading of output operator as, cout<<“The sum of “<<value1<< “and “<<value2<<“ is “ <<value1+value2; Object Oriented Programming using C++ - Preetha V AP/CSE 106
CASCADING I/O OPERATOR For Example INPUT OPERATOR cout<<“Enter the two values “; cin >>value1; cin >>value2; This can be using cascading of input operator as, cout<<“Enter the two values “; cin >>value1>>value2; Object Oriented Programming using C++ - Preetha V AP/CSE 107
Arrays and Strings Object Oriented Programming using C++ - Preetha V AP/CSE
Arrays Array - a collection of a fixed number of components wherein all of the components have the same data type One-dimensional array - an array in which the components are arranged in a list form The general form of declaring a one-dimensional array is: dataType arrayName[intExp]; where intExp is any expression that evaluates to a positive integer 109 Object Oriented Programming using C++ - Preetha V AP/CSE
Declaring an array The statement int num[5]; declares an array num of 5 components of the type int The components are num[0] , num[1] , num[2] , num[3] , and num[4] 110 Object Oriented Programming using C++ - Preetha V AP/CSE
111 Object Oriented Programming using C++ - Preetha V AP/CSE
Accessing Array Components The general form (syntax) of accessing an array component is: arrayName[indexExp] where indexExp , called index , is any expression whose value is a nonnegative integer Index value specifies the position of the component in the array The [] operator is called the array subscripting operator The array index always starts at 112 Object Oriented Programming using C++ - Preetha V AP/CSE
113 Object Oriented Programming using C++ - Preetha V AP/CSE
114 Object Oriented Programming using C++ - Preetha V AP/CSE
115 Object Oriented Programming using C++ - Preetha V AP/CSE
116 Object Oriented Programming using C++ - Preetha V AP/CSE
Processing One-Dimensional Arrays Some basic operations performed on a one-dimensional array are: Initialize Input data Output data stored in an array Find the largest and/or smallest element Each operation requires ability to step through the elements of the array Easily accomplished by a loop 117 Object Oriented Programming using C++ - Preetha V AP/CSE
Accessing Array Components (continued) Consider the declaration int list[100]; //list is an array //of the size 100 int i; This for loop steps through each element of the array list starting at the first element for (i = 0; i < 100; i++) //Line 1 //process list[i] //Line 2 118 Object Oriented Programming using C++ - Preetha V AP/CSE
Accessing Array Components (continued) If processing list requires inputting data into list The statement in Line 2 takes the from of an input statement, such as the cin statement for (i = 0; i < 100; i++) //Line 1 cin >> list[i]; 119 Object Oriented Programming using C++ - Preetha V AP/CSE
120 Object Oriented Programming using C++ - Preetha V AP/CSE
121 Object Oriented Programming using C++ - Preetha V AP/CSE
Array Index Out of Bounds If we have the statements: double num[10]; int i; The component num[i] is a valid index if i = 0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , or 9 The index of an array is in bounds if the index >=0 and the index <= ARRAY_SIZE-1 122 Object Oriented Programming using C++ - Preetha V AP/CSE
Array Index Out of Bounds (continued) If either the index < 0 or the index > ARRAY_SIZE-1 then we say that the index is out of bounds There is no guard against indices that are out of bounds C++ does not check if the index value is within range 123 Object Oriented Programming using C++ - Preetha V AP/CSE
Array Initialization As with simple variables Arrays can be initialized while they are being declared When initializing arrays while declaring them Not necessary to specify the size of the array Size of array is determined by the number of initial values in the braces For example: double sales[] = {12.25, 32.50, 16.90, 23, 45.68}; 124 Object Oriented Programming using C++ - Preetha V AP/CSE
Partial Initialization The statement int list[10] = {0}; declares list to be an array of 10 components and initializes all components to zero The statement int list[10] = {8, 5, 12}; declares list to be an array of 10 components, initializes list[0] to 8 , list[1] to 5 , list[2] to 12 and all other components are initialized to 125 Object Oriented Programming using C++ - Preetha V AP/CSE
Partial Initialization (continued) The statement int list[] = {5, 6, 3}; declares list to be an array of 3 components and initializes list[0] to 5 , list[1] to 6 , and list[2] to 3 The statement int list[25]= {4, 7}; declares list to be an array of 25 components The first two components are initialized to 4 and 7 respectively All other components are initialized to 126 Object Oriented Programming using C++ - Preetha V AP/CSE
Restrictions on Array Processing Assignment does not work with arrays In order to copy one array into another array we must copy component-wise 127 Object Oriented Programming using C++ - Preetha V AP/CSE
Restrictions on Array Processing (continued) 128 Object Oriented Programming using C++ - Preetha V AP/CSE
Arrays as Parameters to Functions Arrays are passed by reference only The symbol & is not used when declaring an array as a formal parameter The size of the array is usually omitted 129 Object Oriented Programming using C++ - Preetha V AP/CSE
Arrays as Parameters to Functions (continued) If the size of one-dimensional array is specified when it is declared as a formal parameter It is ignored by the compiler The reserved word const in the declaration of the formal parameter can prevent the function from changing the actual parameter 130 Object Oriented Programming using C++ - Preetha V AP/CSE
131 Object Oriented Programming using C++ - Preetha V AP/CSE
132 Object Oriented Programming using C++ - Preetha V AP/CSE
133 Object Oriented Programming using C++ - Preetha V AP/CSE
134 Object Oriented Programming using C++ - Preetha V AP/CSE
Base Address of an Array The base address of an array is the address, or memory location of the first array component If list is a one-dimensional array base address of list is the address of the component list[0] When we pass an array as a parameter base address of the actual array is passed to the formal parameter Functions cannot return a value of the type array 135 Object Oriented Programming using C++ - Preetha V AP/CSE
Parallel Arrays Two (or more) arrays are called parallel if their corresponding components hold related information For example: int studentId[50]; char courseGrade[50]; 136 Object Oriented Programming using C++ - Preetha V AP/CSE
Two-Dimensional Arrays Two-dimensional Array : a collection of a fixed number of components arranged in two dimensions All components are of the same type The syntax for declaring a two-dimensional array is: dataType arrayName[intexp1][intexp2]; where intexp1 and intexp2 are expressions yielding positive integer values 137 Object Oriented Programming using C++ - Preetha V AP/CSE
Two-Dimensional Arrays (continued) The two expressions intexp1 and intexp2 specify the number of rows and the number of columns, respectively, in the array Two-dimensional arrays are sometimes called matrices or tables 138 Object Oriented Programming using C++ - Preetha V AP/CSE
139 Object Oriented Programming using C++ - Preetha V AP/CSE
Accessing Array Components The syntax to access a component of a two-dimensional array is: arrayName[indexexp1][indexexp2] where indexexp1 and indexexp2 are expressions yielding nonnegative integer values indexexp1 specifies the row position and indexexp2 specifies the column position 140 Object Oriented Programming using C++ - Preetha V AP/CSE
141 Object Oriented Programming using C++ - Preetha V AP/CSE
Initialization Like one-dimensional arrays Two-dimensional arrays can be initialized when they are declared To initialize a two-dimensional array when it is declared Elements of each row are enclosed within braces and separated by commas All rows are enclosed within braces For number arrays, if all components of a row are not specified, the unspecified components are initialized to zero 142 Object Oriented Programming using C++ - Preetha V AP/CSE
Processing Two-Dimensional Arrays A two-dimensional array can be processed in three different ways: Process the entire array Process a particular row of the array, called row processing Process a particular column of the array, called column processing 143 Object Oriented Programming using C++ - Preetha V AP/CSE
Processing Two-Dimensional Arrays (continued) Each row and each column of a two-dimensional array is a one-dimensional array When processing a particular row or column of a two-dimensional array we use algorithms similar to processing one-dimensional arrays 144 Object Oriented Programming using C++ - Preetha V AP/CSE
145 Object Oriented Programming using C++ - Preetha V AP/CSE
146 Object Oriented Programming using C++ - Preetha V AP/CSE
147 Object Oriented Programming using C++ - Preetha V AP/CSE
148 Object Oriented Programming using C++ - Preetha V AP/CSE
149 Object Oriented Programming using C++ - Preetha V AP/CSE
Passing Two-Dimensional Arrays as Parameters to Functions Two-dimensional arrays can be passed as parameters to a function By default, arrays are passed by reference The base address, which is the address of the first component of the actual parameter, is passed to the formal parameter 150 Object Oriented Programming using C++ - Preetha V AP/CSE
Two-Dimensional Arrays Two-dimensional arrays are stored in row order The first row is stored first, followed by the second row, followed by the third row and so on When declaring a two-dimensional array as a formal parameter can omit size of first dimension, but not the second Number of columns must be specified 151 Object Oriented Programming using C++ - Preetha V AP/CSE
Multidimensional Arrays Multidimensional Array : collection of a fixed number of elements (called components) arranged in n dimensions (n >= 1) Also called an n-dimensional array General syntax of declaring an n-dimensional array is: dataType arrayName[intExp1][intExp2]...[intExpn]; where intExp1 , intExp2 , … are constant expressions yielding positive integer values 152 Object Oriented Programming using C++ - Preetha V AP/CSE
Multidimensional Arrays (continued) The syntax for accessing a component of an n -dimensional array is: arrayName[indexExp1][indexExp2]...[indexExpn] where indexExp1,indexExp2 ,..., and indexExpn are expressions yielding nonnegative integer values indexExpi gives the position of the array component in the i th dimension 153 Object Oriented Programming using C++ - Preetha V AP/CSE
Multidimensional Arrays (continued) When declaring a multi-dimensional array as a formal parameter in a function can omit size of first dimension but not other dimensions As parameters, multi-dimensional arrays are passed by reference only A function cannot return a value of the type array There is no check if the array indices are within bounds 154 Object Oriented Programming using C++ - Preetha V AP/CSE
Summary An array is a structured data type with a fixed number of components Every component is of the same type Components are accessed using their relative positions in the array Elements of a one-dimensional array are arranged in the form of a list An array index can be any expression that evaluates to a non-negative integer The value of the index must always be less than the size of the array 155 Object Oriented Programming using C++ - Preetha V AP/CSE
Summary (continued) The base address of an array is the address of the first array component In a function call statement, when passing an array as an actual parameter, you use only its name As parameters to functions, arrays are passed by reference only A function cannot return a value of the type array In C++, C-strings are null terminated and are stored in character arrays 156 Object Oriented Programming using C++ - Preetha V AP/CSE
Summary (continued) Commonly used C-string manipulation functions include: strcpy, strcmp, and strlen Parallel arrays are used to hold related information In a two-dimensional array, the elements are arranged in a table form 157 Object Oriented Programming using C++ - Preetha V AP/CSE
Summary (continued) To access an element of a two-dimensional array, you need a pair of indices: one for the row position and one for the column position In row processing, a two-dimensional array is processed one row at a time In column processing, a two-dimensional array is processed one column at a time 158 Object Oriented Programming using C++ - Preetha V AP/CSE
C++ Strings C++ provides following two types of string representations − The C-style character string. The string class type introduced with Standard C++.
The C-Style Character String The C-style character string originated within the C language and continues to be supported within C++. This string is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null .
The following declaration and initialization create a string consisting of the word "Hello". To hold the null character at the end of the array, the size of the character array containing the string is one more than the number of characters in the word "Hello.“ If you follow the rule of array initialization, then you can write the above statement as follows − Char greetings[] = “Hello”; char greeting[6] = {'H', 'e', 'l', 'l', 'o', '\0'};
Following is the memory presentation of above defined string in C/C++ − Actually, you do not place the null character at the end of a string constant. The C++ compiler automatically places the '\0' at the end of the string when it initializes the array. Let us try to print above-mentioned string −
#include <iostream> using namespace std ; int main () { char greeting [ 6 ] = { 'H' , 'e' , 'l' , 'l' , 'o' , '\0’ }; cout << "Greeting message: " ; cout << greeting << endl ; return ; } When the above code is compiled and executed, it produces the following result − Greeting message: Hello
Sr.No Function & Purpose 1 strcpy(s1, s2); Copies string s2 into string s1. 2 strcat(s1, s2); Concatenates string s2 onto the end of string s1. 3 strlen(s1); Returns the length of string s1. 4 strcmp (s1, s2); Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if s1>s2. 5 strchr(s1, ch); Returns a pointer to the first occurrence of character ch in string s1. 6 strstr (s1, s2); Returns a pointer to the first occurrence of string s2 in string s1. C++ supports a wide range of functions that manipulate null-terminated strings −
#include <iostream> #include < cstring > using namespace std ; int main () { char str1 [ 10 ] = "Hello" ; char str2 [ 10 ] = "World" ; char str3 [ 10 ]; int len ; // copy str1 into str3 strcpy ( str3 , str1 ); cout << " strcpy ( str3, str1) : " << str3 << endl ; // concatenates str1 and str2 strcat ( str1 , str2 ); cout << " strcat ( str1, str2): " << str1 << endl ; // total lenghth of str1 after concatenation len = strlen ( str1 ); cout << " strlen (str1) : " << len << endl ; return ; }
The String Class in C++ The standard C++ library provides a string class type that supports all the operations mentioned above, additionally much more functionality. Let us check the following example −
#include <iostream> #include <string> using namespace std ; int main () { string str1 = "Hello" ; string str2 = "World" ; string str3 ; int len ; // copy str1 into str3 str3 = str1 ; cout << "str3 : " << str3 << endl ; // concatenates str1 and str2 str3 = str1 + str2 ; cout << "str1 + str2 : " << str3 << endl ; // total length of str3 after concatenation len = str3 . size (); cout << "str3.size() : " << len << endl ; return ; }
String Comparison C-strings are compared character by character using the collating sequence of the system If we are using the ASCII character set The string "Air" is smaller than the string "Boat" The string "Air" is smaller than the string "An" The string "Bill" is smaller than the string "Billy" The string "Hello" is smaller than "hello" 170 Object Oriented Programming using C++ - Preetha V AP/CSE
Strings are used for storing text. A string variable contains a collection of characters surrounded by double quotes:
Reading and Writing Strings String Input Aggregate operations are allowed for string input cin >> name; stores the next input string in name Strings that contain blanks cannot be read using the extraction operator >> 172 Object Oriented Programming using C++ - Preetha V AP/CSE
Reading and Writing Strings (continued) String Output The statement cout << name; outputs the content of name on the screen The insertion operator << continues to write the contents of name until it finds the null character If name does not contain the null character, then we will see strange output: << continues to output data from memory adjacent to name until '\0' is found 173 Object Oriented Programming using C++ - Preetha V AP/CSE
Approximate Terminology instance = object field = instance variable method = function sending a message to an object =calling a function Object Oriented Programming using C++ - Preetha V AP/CSE 174
C++ Pointers Object Oriented Programming using C++ - Preetha V AP/CSE
The pointer in C++ language is a variable, it is also known as locator or indicator that points to an address of a value. The symbol of an address is represented by a pointer. In addition to creating and modifying dynamic data structures, they allow programs to emulate call-by-reference. One of the principal applications of pointers is iterating through the components of arrays or other data structures. The pointer variable that refers to the same data type as the variable you're dealing with has the address of that variable set to it (such as an int or string). Syntax datatype * var_name ; int * ptr ; // ptr can point to an address which holds int data Object Oriented Programming using C++ - Preetha V AP/CSE
How to use a pointer? Establish a pointer variable. employing the unary operator (&), which yields the address of the variable, to assign a pointer to a variable's address. Using the unary operator (*), which gives the variable's value at the address provided by its argument, one can access the value stored in an address. Object Oriented Programming using C++ - Preetha V AP/CSE
Pointer Object Oriented Programming using C++ - Preetha V AP/CSE
Advantage of pointer Pointer reduces the code and improves the performance, it is used to retrieving strings, trees etc. and used with arrays, structures and functions. 2) We can return multiple values from function using pointer. 3) It makes you able to access any memory location in the computer's memory. Object Oriented Programming using C++ - Preetha V AP/CSE
Symbols used in pointer Symbol Name Description & (ampersand sign) Address operator Determine the address of a variable. ∗ (asterisk sign) Indirection operator Access the value of an address. Object Oriented Programming using C++ - Preetha V AP/CSE
Declaring a pointer int ∗ a; //pointer to int char ∗ c; //pointer to char Object Oriented Programming using C++ - Preetha V AP/CSE
Pointer Example Let's see the simple example of using pointers printing the address and value. #include < iostream > using namespace std ; int main() { int number=30; int ∗ p; p=&number;//stores the address of number variable cout <<"Address of number variable is:"<<&number<< endl ; cout <<"Address of p variable is:"<<p<< endl ; cout <<"Value of p variable is:"<<*p<< endl ; return 0; } Object Oriented Programming using C++ - Preetha V AP/CSE
Output: Address of number variable is:0x7ffccc8724c4 Address of p variable is:0x7ffccc8724c4 Value of p variable is:30 Object Oriented Programming using C++ - Preetha V AP/CSE
Pointer Program to swap 2 numbers without using 3rd variable #include < iostream > using namespace std ; int main() { int a=20,b=10,∗p1=&a,∗p2=&b; cout <<"Before swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<< endl ; ∗p1=∗p1+∗p2; ∗p2=∗p1-∗p2; ∗p1=∗p1-∗p2; cout <<"After swap: ∗p1="<<∗p1<<" ∗p2="<<∗p2<< endl ; return 0; } Object Oriented Programming using C++ - Preetha V AP/CSE
Output: Before swap: ∗p1=20 ∗p2=10 After swap: ∗p1=10 ∗p2=20 Object Oriented Programming using C++ - Preetha V AP/CSE
What are Pointer and string literals? String literals are arrays of character sequences with null ends. The elements of a string literal are arrays of type const char (because characters in a string cannot be modified) plus a terminating null-character. Object Oriented Programming using C++ - Preetha V AP/CSE
What is a void pointer? This unique type of pointer, which is available in C++, stands in for the lack of a kind. Pointers that point to a value that has no type are known as void pointers (and thus also an undetermined length and undetermined dereferencing properties). This indicates that void pointers are very flexible because they can point to any data type. This flexibility has benefits. Direct dereference is not possible with these pointers. Before they may be dereferenced, they must be converted into another pointer type that points to a specific data type. Object Oriented Programming using C++ - Preetha V AP/CSE
What is a invalid pointer? A pointer must point to a valid address, not necessarily to useful items (like for arrays). We refer to these as incorrect pointers. Additionally, incorrect pointers are uninitialized pointers. int *ptr1; int arr [10]; int *ptr2 = arr+20; Here, ptr1 is not initialized, making it invalid, and ptr2 is outside of the bounds of arr , making it likewise weak. (Take note that not all build failures are caused by faulty references.) Object Oriented Programming using C++ - Preetha V AP/CSE
What is a null pointer? A null pointer is not merely an incorrect address; it also points nowhere. Here are two ways to mark a pointer as NULL: Object Oriented Programming using C++ - Preetha V AP/CSE
What is a pointer to a pointer? In C++, we have the ability to build a pointer to another pointer, which might then point to data or another pointer. The unary operator (*) is all that is needed in the syntax for declaring the pointer for each level of indirection. char a; char *b; char ** c; a = 'g'; b = &a; c = &b; Here b points to a char that stores 'g', and c points to the pointer b. Object Oriented Programming using C++ - Preetha V AP/CSE
What are references and pointers? Call-By-Value Call-By-Reference with a Pointer Argument Call-By-Reference with a Reference Argument Object Oriented Programming using C++ - Preetha V AP/CSE
Example #include using namespace std ; // Pass-by-Value int square1( int n) { cout << "address of n1 in square1(): " << &n << "\n"; n *= n; return n; } // Pass-by-Reference with Pointer Arguments void square2( int * n) { cout << "address of n2 in square2(): " << n << "\n"; *n *= *n; } Object Oriented Programming using C++ - Preetha V AP/CSE
// Pass-by-Reference with Reference Arguments void square3( int & n) { cout << "address of n3 in square3(): " << &n << "\n"; n *= n; } Object Oriented Programming using C++ - Preetha V AP/CSE
void example() { // Call-by-Value int n1 = 8; cout << "address of n1 in main(): " << &n1 << "\n"; cout << "Square of n1: " << square1(n1) << "\n"; cout << "No change in n1: " << n1 << "\n"; // Call-by-Reference with Pointer Arguments int n2 = 8; cout << "address of n2 in main(): " << &n2 << "\n"; square2(&n2); cout << "Square of n2: " << n2 << "\n"; cout << "Change reflected in n2: " << n2 << "\n"; Object Oriented Programming using C++ - Preetha V AP/CSE
// Call-by-Reference with Reference Arguments int n3 = 8; cout << "address of n3 in main(): " << &n3 << "\n"; square3(n3); cout << "Square of n3: " << n3 << "\n"; cout << "Change reflected in n3: " << n3 << "\n"; } // Driver program int main() { example(); } Object Oriented Programming using C++ - Preetha V AP/CSE
Output Object Oriented Programming using C++ - Preetha V AP/CSE
UNIT 2 - Classes and Objects Classes and Objects - Class specification: Class Members, Access Specifier , Scope resolution operator- Class Instantiation - Accessing class members- Passing and returning objects - Array of objects – Constructors: Parameterized constructors - Default arguments – Copy Constructor - Constructor overloading, Destructors - new, delete operators - “this” pointer - Friend classes and friend functions. Object Oriented Programming using C++ - Preetha V AP/CSE 197
What is Class? The mechanism that allows you to combine data and the function in a single unit is called a class. Once a class is defined, you can declare variables of that type. A class variable is called object or instance. In other words, a class would be the data type, and an object would be the variable. Classes are generally declared using the keyword class. Object Oriented Programming using C++ - Preetha V AP/CSE 198
What is Class? A class is the collection of related data and function under a single name. A C++ program can have any number of classes. When related data and functions are kept under a class, it helps to visualize the complex problem efficiently and effectively. A class is a definition of an object. It's a type just like int . A class resembles a struct with just one difference : all struct members are public by default. All classes members are private . Object Oriented Programming using C++ - Preetha V AP/CSE 199
What is Class? A class is a user defined type or data structure declared with keyword class that has data and functions (also called methods) as its members whose access is governed by the three access specifiers private , protected or public (by default access to members of a class is private ). A class (declared with keyword class ) in C++ differs from a structure (declared with keyword struct ) as by default, members are private in a class while they are public in a structure. Object Oriented Programming using C++ - Preetha V AP/CSE 200
Defining Class class class_name { Data Members; Methods; }; OR class class_name { private: members1; protected: members2; public: members3; }; Object Oriented Programming using C++ - Preetha V AP/CSE 201
Defining Class private members of a class are accessible only from within other members of the same class . You cannot access it outside of the class. protected members are accessible from members of their same class and also from members of their derived classes . protected members are accessible from other members of the same class (or from their "friends" ), but also from members of their derived classes. Object Oriented Programming using C++ - Preetha V AP/CSE 202
Defining Class public members are accessible from anywhere where the object is visible. By default, all members of a class declared with the class keyword have private access for all its members. Therefore, any member that is declared before one other class specifies automatically has private access. Object Oriented Programming using C++ - Preetha V AP/CSE 203
Defining Member Function of Class Member functions can be defined in two ways, Inside the class Outside the class Object Oriented Programming using C++ - Preetha V AP/CSE 204
Object Declaration Once a class is defined, you can declare objects of that type. The syntax for declaring a object is the same as that for declaring any other variable. The following statements declare two objects of type circle : Circle c1, c2; Circle is class and c1 and c2 are the objects. Once the class is defined you can define any number of objects. Object Oriented Programming using C++ - Preetha V AP/CSE 205
Object Declaration Accessing Class Members Once an object of a class is declared, it can access the public members of the class using ( . ) dot membership operator . c1.setRadius(2.5); Object Oriented Programming using C++ - Preetha V AP/CSE 206
Access modifiers Access modifiers (or access specifiers ) are keywords in object-oriented languages that set the accessibility of classes, methods, and other members. Access modifiers are a specific part of programming language syntax used to facilitate the encapsulation of components Object Oriented Programming using C++ - Preetha V AP/CSE 207
Access modifiers C++ uses the three modifiers called public , protected , and private . Java has public , package , protected , and private . Object Oriented Programming using C++ - Preetha V AP/CSE 208
Local Classes in C++ A class declared inside a function becomes local to that function and is called Local Class in C++. For example, in the following program, Test is a local class in fun(). void fun() { class Test // local to fun { Int mark1; Int mark3; /* members of Test class */ }; } Object Oriented Programming using C++ - Preetha V AP/CSE 209
Global Classes in C++ A class declared outside the body of all the function in a program is called Global Class in C++. For example class Sample // class name { int x; //member variables or data members public: void readx () // function name or member function declaration { cin >>x; } }; void main() { Sample s1; s1.readx(); } Object Oriented Programming using C++ - Preetha V AP/CSE 210
Local and Global Objects in C++ class Sample { int x; public: void readx () { cin >>x; } }; Sample s1; // Global Object void main() { Sample s2; // Local Object s1.readx(); } Object Oriented Programming using C++ - Preetha V AP/CSE 211
“this” Pointer “this” Pointer Every object in C++ has access to its own address through an important pointer called this pointer. The this pointer is an implicit parameter to all member functions. Therefore, inside a member function, this may be used to refer to the invoking object. Friend functions do not have a this pointer, because friends are not members of a class. Only member functions have a this pointer. Object Oriented Programming using C++ - Preetha V AP/CSE 212
Let us try the following example to understand the concept of this pointer: #include < iostream > using namespace std ; class Box { public: // Constructor definition Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << endl ; length = l; breadth = b; Object Oriented Programming using C++ - Preetha V AP/CSE 213
height = h; } double Volume() { return length * breadth * height; } int compare(Box box) { return this->Volume() > box.Volume (); } private: double length; double breadth; double height; // Length of a box // Breadth of a box // Height of a box }; Object Oriented Programming using C++ - Preetha V AP/CSE 214
int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 if(Box1.compare(Box2)) { cout << "Box2 is smaller than Box1" << endl ; } else { cout << "Box2 is equal to or larger than Box1" << endl ; } return 0; } When the above code is compiled and executed, it produces the following result: Constructor called. Constructor called. Box2 is equal to or larger than Box1 Object Oriented Programming using C++ - Preetha V AP/CSE 215
CONSTRUCTOR A class constructor is a special member function of a class that is executed whenever we create new objects of that class A constructor will have exact same name as the class and it does not have any return type at all, not even void. Constructors can be very useful for setting initial values for certain member variables. Types of Constructor Default Constructor Overloaded Constructor Parameterized Constructor Copy Constructor Object Oriented Programming using C++ - Preetha V AP/CSE 216
Scope resolution operator Member functions can be defined within the class definition or separately using scope resolution operator :: Defining a member function within the class definition declares the function inline , even if you do not use the inline specifier . So either you can define Volume () function as below: Object Oriented Programming using C++ - Preetha V AP/CSE 217
class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box double getVolume (void) { return length * breadth * height; } }; If you like, you can define the same function outside the class using the scope resolution operator (::) as follows: Syntax: datatype class name::function name() Object Oriented Programming using C++ - Preetha V AP/CSE 218
Example: double Box:: getVolume (void) { return length * breadth * height; } Here, only important point is that you would have to use class name just before operator. A member function will be called using a dot operator (.) on a object where it will manipulate data related to that object only as follows: Box myBox ; // Create an object myBox.getVolume (); // Call member function for the object Object Oriented Programming using C++ - Preetha V AP/CSE 219
Let us put above concepts to set and get the value of different class members in a class: #include < iostream > using namespace std ; class Box { public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box //Member functions declaration double getVolume (void); void setLength ( double len ); void setBreadth ( double bre ); void setHeight ( double hei ); }; Object Oriented Programming using C++ - Preetha V AP/CSE 220
//Member functions definitions double Box:: getVolume (void) { return length * breadth * height; } void Box:: setLength ( double len ) { length = len ; } void Box:: setBreadth ( double bre ) { breadth = bre ; } void Box:: setHeight ( double hei ) { height = hei ; } Object Oriented Programming using C++ - Preetha V AP/CSE 221
// Main function for the program int main( ) { Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box double volume = 0.0; // Store the volume of a box here // box 1 specification Box1.setLength(6.0); Box1.setBreadth(7.0); Box1.setHeight(5.0); // box 2 specification Box2.setLength(12.0); Box2.setBreadth(13.0); Box2.setHeight(10.0); // volume of box 1 volume = Box1.getVolume(); cout << "Volume of Box1 : " << volume << endl ; Object Oriented Programming using C++ - Preetha V AP/CSE 222
// volume of box 2 volume = Box2.getVolume(); cout << "Volume of Box2 : " << volume<< endl ; return 0; } When the above code is compiled and executed, it produces the following result: Volume of Box1 : 210 Volume of Box2 : 1560 Object Oriented Programming using C++ - Preetha V AP/CSE 223
Need for constructor Constructor is special member functions. It is a function used to initialize the object itself. The data within the class cannot be initialized at that time of declaration in class. Constructor has the same name as the name of the class . This is because the declaration of a class serves only as a template, and no memory is allocated at the time of declaration. This problem can be solved by writing an initializing function – a constructor. Constructor is a basically a function used to initialize variables, to allocate memory and soon. This function will be automatically called as soon as an object is created. There is no need to call the function to initialize the variables. Object Oriented Programming using C++ - Preetha V AP/CSE 224
Constructor Declaration Class Class_name { Private: Public: Class_name (); // constructor // student(); ~ Class_name (); //destructor // ~ student(); }; Object Oriented Programming using C++ - Preetha V AP/CSE 225
How constructors are different from a normal member function? A constructor is different from normal functions in following ways: Constructor has same name as the class itself Constructors don’t have return type A constructor is automatically called when an object is created. If we do not specify a constructor, C++ compiler generates a default constructor for us (expects no parameters and has an empty body). Object Oriented Programming using C++ - Preetha V AP/CSE 226
Default Constructors: Default constructor is the constructor which doesn’t take any argument. It has no parameters. #include < iostream > using namespace std ; class construct { public: int a, b; construct() // Default Constructor { a = 10; b = 20; } }; int main() { // Default constructor called automatically // when the object is created construct c; cout << "a: "<< c.a << endl << "b: "<< c.b ; return 1; } Output: a: 10 b: 20 Object Oriented Programming using C++ - Preetha V AP/CSE 227
Parameterized Constructors : It is possible to pass arguments to constructors . Typically, these arguments help initialize an object when it is created. To create a parameterized constructor, simply add parameters to it the way you would to any other function. When you define the constructor’s body, use the parameters to initialize the object . int main() { // Constructor called Point p1(10, 15); // Access values assigned by constructor cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); return 0; } Output: p1.x = 10, p1.y = 15 Object Oriented Programming using C++ - Preetha V AP/CSE 228 #include< iostream > using namespace std ; class Point { private : int x, y; public : Point( int x1, int y1) // Parameterized Constructor { x = x1; x=10 y = y1; y=15 } int getX () { return x; } int getY () { return y; } };
Copy Constructor : A copy constructor is a member function which initializes an object using another object of the same class. A copy constructor has the following general function prototype: ClassName ( const ClassName & old_obj ); #include< iostream > using namespace std ; class Point { private: int x, y; public: Point( int x1, int y1) { x = x1; y = y1; } Point( const Point &p2) {x = p2.x; y = p2.y; } // Copy constructor int getX () { return x; } int getY () { return y; } }; int main() { Point p1(10, 15); // Normal constructor is called here Point p2 = p1; // Copy constructor is called here // Let us access values assigned by constructors cout << "p1.x = " << p1.getX() << ", p1.y = " << p1.getY(); cout << "\np2.x = " << p2.getX() << ", p2.y = " << p2.getY(); return 0; } Output: p1.x = 10, p1.y = 15 p2.x = 10, p2.y = 15 Object Oriented Programming using C++ - Preetha V AP/CSE 229
#include< iostream > using namespace std ; class Point { private: int x, y; public: Point( int x1, int y1) { x = x1; y = y1; } Point( const Point &p2) { x = p2.x; y = p2.y; } // Copy constructor int getX () { return x; } int getY () { return y; } }; Object Oriented Programming using C++ - Preetha V AP/CSE 230
Copy Constructor #include< iostream > using namespace std ; class Sample { private: int x, y; //data members public: Sample( int x1, int y1) { x = x1; y = y1; } /* Copy constructor */ Sample ( const Sample & sam ) { x = sam.x ; y = sam.y ; } void display() { cout <<x<<" "<<y<< endl ; } }; int main() { Sample obj1(10, 15); // Normal const Sample obj2 = obj1; // Copy constructor cout <<"Normal constructor : "; obj1.display(); cout <<"Copy constructor : "; obj2.display(); return 0; } Output: Normal constructor : 10 15 Copy constructor : 10 15 Object Oriented Programming using C++ - Preetha V AP/CSE 231
Constructor Overloading in C++ In C++, We can have more than one constructor in a class with same name, as long as each has a different list of arguments. This concept is known as Constructor Overloading and is quite similar to function overloading. Overloaded constructors essentially have the same name (name of the class) and different number of arguments. A constructor is called depending upon the number and type of arguments passed. While creating the object, arguments must be passed to let compiler know, which constructor needs to be called. Object Oriented Programming using C++ - Preetha V AP/CSE 232
Parameterized Constructor: #include <iostream> using namespace std; class Line { public: void setLength ( double len ); double getLength ( void ); Line(double len ); // This is the constructor private: double length; }; // Member functions definitions including constructor Line::Line( double len ) { cout << "Object is being created, length = " << len << endl; length = len ; } void Line:: setLength ( double len ) { length = len ;} double Line:: getLength ( void ) { return length;} // Main function for the program int main( ) { Line line(10.0); // get initially set length. cout << "Length of line : " << line.getLength () <<endl; // set line length again line.setLength (6.0); cout << "Length of line : " << line.getLength () <<endl; return 0; } OUTPUT: Object is being created, length = 10 Length of line : 10 Length of line : 6 233 Object Oriented Programming using C++ - Preetha V AP/CSE
Destructors in C++ What is destructor? Destructor is a member function which destructs or deletes an object. When is destructor called? A destructor is automatically called when: 1) The program finished execution. 2) When a scope (the { } parenthesis) containing local variable ends. 3) When you call the delete operator. How destructors are different from a normal member function? Destructors have same name as the class preceded by a tilde (~) Destructors don’t take any argument and don’t return anything. Object Oriented Programming using C++ - Preetha V AP/CSE 234
Destructors: Destructor is a member function which destructs or deletes an object. Destructor called? A destructor function is called automatically when the object goes out of scope: (1) the function ends (2) the program ends (3) a block containing local variables ends (4) a delete operator is called Object Oriented Programming using C++ - Preetha V AP/CSE 235
Destructors - new, delete operators How destructors are different from a normal member function? Destructors have same name as the class preceded by a tilde (~) Destructors don’t take any argument and don’t return anything Object Oriented Programming using C++ - Preetha V AP/CSE 236
class String { private : char *s; int size; public : String( char *); // constructor ~String(); // destructor }; String::String( char *c) { size = strlen (c); s = new char [size+1]; strcpy ( s,c ); } String::~String() { delete []s; } Object Oriented Programming using C++ - Preetha V AP/CSE 237
STATIC MEMBER In normal situations when we instantiate objects of a class each object gets its own copy of all normal member variables. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member . This means one single copy of that data member is shared between all objects of that class . All static data is initialized to zero when the first object is created, if no other initialization is present. Static data members can be initialized outside the class using the scope resolution operator (::) to identify which class it belongs to. Since Static data members are class level variables , we do not require the object to access these variables and they can be accessed simply by using the class name and scope resolution(::) operator with the variable name to access its value. Also a static data member cannot be private. A very common use of static data members is to keep a count of total objects of a particular class (program counter kind of application) Object Oriented Programming using C++ - Preetha V AP/CSE 238
STATIC MEMBER Object Oriented Programming using C++ - Preetha V AP/CSE 239
STATIC MEMBER Static Data member has the following properties: It is initialized by zero when first object of class is created. Only one copy of static data member is created for the entire class and all object share the same copy. Its scope is within class but its lifetime is entire program. They are used to store the value that are common for all the objects. Static variable can be declared using the following syntax: static data-type variable-name; The above syntax only declare the static variable. We can initialize static variable by using following syntax: data-type class-name :: variable-name = initial-value ; Along with the definition we can also initialize the static variable. If static data members (variables) are declared under the public section than it can be accessed from outside the class and if it is declared in private section than it can only be accessed within the class itself. Static variables are also known as class variables because they are not the variables of any particular class. Object Oriented Programming using C++ - Preetha V AP/CSE 240
Static Member Function By declaring a function member as static, you make it independent of any particular object of the class. A static member function can be called even if no objects of the class exist and the static functions are accessed using only the class name and the scope resolution operator :: A static member function can only access static data member, other static member functions and any other functions from outside the class. Static member functions have a class scope and they do not have access to the this pointer of the class. You could use a static member function to determine whether some objects of the class have been created or not. Object Oriented Programming using C++ - Preetha V AP/CSE 241
Static Member Function Static member function has following properties: A static function can be access only by other static data member (variables) and function declared in the class. A static function is called using class name instead of object name. Object Oriented Programming using C++ - Preetha V AP/CSE 242
private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Initialize static member of class Box int Box::objectCount = 0; int main(void) { Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 // Print total number of objects. cout << "Total objects: " << Box::objectCount << endl; return 0; } OUTPUT: Constructor called. Constructor called. Total objects: 2 243 #include <iostream> using namespace std; class Box { public: static int objectCount; // Constructor definition Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // Increase every time object is created objectCount++; } double Volume() { return length * breadth * height; } Object Oriented Programming using C++ - Preetha V AP/CSE
static int getCount () { return objectCount; } private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; // Initialize static member of class Boxint Box::objectCount = 0; int main(void) { // Print total number of objects before creating object. cout << " Inital Stage Count: " << Box:: getCount () << endl; Box Box1(3.3, 1.2, 1.5); // Declare box1 Box Box2(8.5, 6.0, 2.0); // Declare box2 // Print total number of objects after creating object. cout << "Final Stage Count: " << Box:: getCount () << endl; return 0; } OUTPUT: Inital Stage Count: 0 Constructor called. Constructor called. Final Stage Count: 2 244 #include <iostream> using namespace std; class Box { public: static int objectCount; // Constructor definition Box(double l=2.0, double b=2.0, double h=2.0) { cout <<"Constructor called." << endl; length = l; breadth = b; height = h; // Increase every time object is created objectCount++; } double Volume() { return length * breadth * height; } Object Oriented Programming using C++ - Preetha V AP/CSE
STORAGE CLASSES: A storage class defines the scope (visibility) and life-time of variables and/or functions within a C++ Program. These specifiers precede the type that they modify. There are following storage classes, which can be used in a C++ Program auto register static extern 245 Object Oriented Programming using C++ - Preetha V AP/CSE
Array of Objects An object of class represents a single record in memory, if we want more than one record of class type, we have to create an array of class or object. As we know, an array is a collection of similar type, therefore an array can be a collection of class type. Object Oriented Programming using C++ - Preetha V AP/CSE 246
Syntax of Array of Objects class class-name { datatype var1; datatype var2; - - - - - - - - - - datatype varN ; method1(); method2(); - - - - - - - - - - methodN (); }; class-name obj [ size ]; Object Oriented Programming using C++ - Preetha V AP/CSE 247
void PutData () //Statement 2 : Defining PutData () { cout <<"\n"<<Id<<"\t"<<Name<<"\t"<<Age<<"\t"<<Salary; } }; void main() { int i ; Employee E[3]; //Statement 3 : Creating Array of 3 Employees for( i =0;i<3;i++) { cout <<"\ nEnter details of "<<i+1<<" Employee"; E[ i ]. GetData (); } cout <<"\ nDetails of Employees"; for( i =0;i<3;i++) E[ i ]. PutData (); } Object Oriented Programming using C++ - Preetha V AP/CSE 248 #include< iostream.h > #include< conio.h > class Employee { int Id; char Name[25]; int Age; long Salary; public: void GetData () //Statement 1 : Defining GetData () { cout <<"\n\ tEnter Employee Id : "; cin >>Id; cout <<"\n\ tEnter Employee Name : "; cin >>Name; cout <<"\n\ tEnter Employee Age : "; cin >>Age; cout <<"\n\ tEnter Employee Salary : "; cin >>Salary; }
Friend function A friend function of a class is defined outside that class scope but it has the right to access all private and protected members of the class. A friend can be a function, function template, or member function, or a class or class template, in which case the entire class and all of its members are friends. Declaration of friend function in C++ class class_name { ... .. ... friend return_type function_name (argument/s); ... .. ... } Object Oriented Programming using C++ - Preetha V AP/CSE 249
Friend function Friend Function Definition: If a function is friend function of a class, that friend function is not the actual member of the class. But which function has rights to access to all private and protected members (variables and functions). Need of Friend Function According to the data hiding concept in C++, no one has the permission to access private and protected members from outside the class . If a developer needs access to the private or protected members, then the developer can use friend functions. A friend function provides privileges to access all the private and protected members of the class. Object Oriented Programming using C++ - Preetha V AP/CSE 250
Friend function Object Oriented Programming using C++ - Preetha V AP/CSE 251
Friend Function Syntax class class_name { //Member variables and Function // Friend Function Declaration friend return_type friend_function_name (arguments / objects); } // Friend Function Definition return_type friend_function_name (arguments / objects) { // Friend function has privileges to access all private and protected members of the class } Object Oriented Programming using C++ - Preetha V AP/CSE 252
Friend Function Characteristics The friend function is not in class scope. It should be declared inside the class with ‘friend’ keyword. It can be defined anywhere in the program and outside of the class like a normal function. But friend keyword must be used in the function definition. It is not in class scope. So it cannot be called by objects of the class. It can be called like a normal function. Usually, it has class objects as arguments. It cannot access member variables or functions directly, but can only be accessed by the help of the objects of the class. It can be declared with any access specifier and the access specifier does not have any impact on the friend function. Object Oriented Programming using C++ - Preetha V AP/CSE 253
To declare a function as a friend of a class , precede the function prototype in the class definition with keyword friend class Box { double width; public: double length; friend void printWidth( Box box ); void setWidth( double wid ); }; Object Oriented Programming using C++ - Preetha V AP/CSE 254
To declare all member functions of class ClassTwo as friends of class ClassOne, place a following declaration in the definition of class ClassOne friend class Class Two; Object Oriented Programming using C++ - Preetha V AP/CSE 255
#include <iostream> using namespace std; class Box { double width; public: friend void printWidth( Box box ); void setWidth( double wid ); }; // Member function definition void Box::setWidth( double wid ) { width = wid; } // Note: printWidth() is not a member function of any class. void printWidth( Box box ) { /* Because printWidth() is a friend of Box, it can directly access any member of this class */ cout << "Width of box : " << box.width << endl ; } // Main function for the program int main() { Box box ; // set box width without member function box.setWidth (10.0); // Use friend function to print the width. printWidth( box ); return 0; } Object Oriented Programming using C++ - Preetha V AP/CSE 256
END OF UNIT 1, 2 Object Oriented Programming using C++ - Preetha V AP/CSE 257