Download presentation
Presentation is loading. Please wait.
Published byAshlie Anthony Modified over 9 years ago
1
Object Oriented Programming with C++ Diploma in Computer System Design
2
Course Outline Chapter 1. Introduction to Object-Oriented Programming Chapter 2. Introduction to C++ Chapter 3. Functions in C++ Chapter 4. Classes and Objects Chapter 5. Constructors and Destructors Chapter 6. Operator Overloading and Type Conversion Chapter 7. Inheritance in C++ Chapter 8. Pointers and Virtual Functions & Polymorphism Chapter 9. Managing Console I/O Operations Chapter 10. Working with Files
3
Chapter 2 Introduction to C++ What is C++ A Simple C++ program Structure of a C++ program Tokens Data Types Expressions Control Structures
4
C++ is an OO Programming language. Initially named ‘C with classes’, C++ was developed by Bjarne Stroustrup at AT&T Bell Laboratories, USA in the early 80’s. C++ is a superset of C. The three most important facilities that C++ adds on to C are classes, function overloading, and operator overloading. These features enable us to create abstract data types, inherit properties from existing data types and support polymorphism. What is C++
5
A Simple C++ program 1 // example1.cpp 2 // Displaying a String. 3 #include // include header file 4 int main() 5 { 6cout << “C++ is better C.”; // C++ statement 7return 0; 8 } 9 // End of example Program Features The example1 contains only one function, main(). Execution begins at main(). Every C++ program must have a main(). Like C, the C++ statements terminate with semicolons. C++ is better C.
6
Comments Single line comment Example: //This is an example of C++ program single line comment. Multiline comments Example: // This is an example of // C++ program // multiline comment Example: /* This is an example of C++ program multiline comment. */
7
The iostream.h File The above include directive causes the preprocessor to add the contents of the iostream.h file to the program. It contains declarations for the identifier cout and the operator <<. The header file iostream.h should be included at the beginning of all programs that use input/output statements. We must include appropriate header files depending on the contents of the program. For example, if we want to use printf() and scanf(), the header file stdio.h should be included. 3 #include // include header file
8
Output Operator The identifier cout (pronounced as ‘C out’) is a predefined object that represents the standard output stream in C++. Here, the standard output stream represents the screen. It is also possible to redirect the output to other output devices. The operator << is called the insertion operator. It inserts the contents of the variable on its right to the output stream on its left. 6cout << “C++ is better C.”; // C++ statement
9
Input Operator 1 // example2.cpp 2 // Input two numbers. 3 #include // include header file 4 int main() 5 { 6 float number1, number2; 7cout << “Enter two numbers separated by a space : ”; 8cin >> number1; 9cin >> number2; 10return 0; 11 } 12 // End of example Enter two numbers separated by a space : 2.5 6.7
10
Input Operator The identifier cin (pronounced as ‘C in’) is a predefined object that represents the standard input stream in C++. Here, the standard input stream represents the keyboard. The operator >> is called the extraction operator. It extracts the value from the keyboard and assigns it to the variable on its right.
11
Cascading I/O Operator 1 // example3.cpp 2 // Input two numbers and display them. 3 #include // include header file 4 int main() 5 { 6 float number1, number2; 7cout << endl; 8cout << “Enter two numbers separated by a space : ”; 9cin >> number1 >> number2; 10cout << “Number1 : ” << number1 << “\n” << “Number2 : ” << number2; 11return 0; 12 } 13 // End of example Enter two numbers separated by a space : 2.5 6.7 Number1 : 2.5 Number2 : 6.7
12
Return Statement In C++, main() returns an integer type value to the operating system. Every main() in C++ should end with a return(0) statement; otherwise a warning or an error might occur. Turbo C++ gives a warning and then compiles and executes the program.
13
An example with Class 1 // example4.cpp 2 // A Class example. 3 #include // include header file 4 class person // new data type 5 { 6char name[30]; 7 int age; 8 public : 9 void getdata(void); 10 void display(void); 11 } 12 13 void person : : getdata(void) // member function 14 { 15cout << endl; 16cout > name; 17cout > age; 18 }
14
An example with Class contd… 19 void person : : display(void) // member function 20 { 21cout << “\nName : ” << name; 22cout << “\nAge : ” << age; 23 } 24 25 int main() 26 { 27person p;// object of type person 28p.getdata(); 29p.display(); 30return 0; 31 } Enter name : Lalith Enter age : 24 Name : Lalith Age : 24
15
An example with Class contd… The program defines person as a new class. The class person includes two basic data type items and two functions to operate on that data. The two basic data type items are called member data. The two functions are called member functions. The main program uses class person to create objects. Class variables are the objects. In example4, p is an object of class person. Class objects are used to call the functions defined in that class.
16
Structure of a C++ Program A typical C++ program would contain four sections: Include files Class declaration Class function definitions Main program These sections may be placed in separate code files and then compiled independently or jointly.
17
Structure of a C++ Program It is a common practice to organize a program into three separate code files. Class declarations are placed in a header file. The definitions of member functions of the class are placed in another file. Main program that uses the class is placed in a third file which “includes” the previous two files as well as any other files required. This approach enables the programmer to separate the class declaration from member function definition(s).
18
Creating the Source File Like C programs, C++ programs can be created using any text editor. Turbo C++ provides an integrated environment for developing and editing programs. C++ implementations use extensions such as,.cpp Turbo C++ and Borland C++ use.c for C programs and.cpp (C plus plus) for C++ programs.
19
Review Questions & Exercises Find errors, if any, in the following C++ statements: (a) cout << “x=”x; (b) cin >>x;>>y; (c) cout << \n “Name: ” <<name; (d) cout > x; Write a program to enter marks for the following three subjects and then display the following output (as it is) using a single cout statement. Maths= 90 Physics= 77 Chemistry= 69
20
Tokens A token is a language element that can be used in constructing higher-level language constructs. C++ has the following Tokens: Keywords (Reserved words) Identifiers Constants Strings (String literals) Punctuators Operators
21
Keywords Implements specific C++ language features. They are explicitly reserved identifiers and cannot be used as names for the program variables or other user-defined program elements. Following table is a list of keywords in C++: asmdeleteifreturntry autodoinlineshorttypedef breakdoubleintsignedunion caseelselongsizeofunsigned catchenumnewstaticvirtual charexternoperatorstructvoid classfloatprivateswitchvolatile constforprotectedtemplatewhile continuefriendpublicthis defaultgotoregisterthrow
22
Identifiers Identifiers refer to the names of variables, functions, arrays, classes etc. Rules for constructing identifiers: Only alphabetic characters, digits and underscores are permitted. The name cannot start with a digit. Uppercase and lowercase letters are distinct. A declared keyword cannot be used as a variable name. There is virtually no length limitation. However, in many implementations of C++ language, the compilers recognize only the first 32 characters as significant. There can be no embedded blanks.
23
Constants Constants are entities that appear in the program code as fixed values. There are four classes of constants in C++: Integer Floating-point Character Enumeration Integer Constants Positive or negative whole numbers with no fractional part. Commas are not allowed in integer constants. E.g.: const int size = 15; const length = 10; A const in C++ is local to the file where it is created. To give const value external linkage so that it can be referenced from another file, define it as an extern in C++. E.g.: extern const total = 100;
24
Constants Floating-point Constants Floating-point constants are positive or negative decimal numbers with an integer part, a decimal point, and a fractional part. They can be represented either in conventional or scientific notation. For example, the constant 17.89 is written in conventional notation. In scientific notation it is equivalent to 0.1789X102. This is written as 0.1789E+2 or as 0.1789e+2. Here, E or e stands for ‘exponent’. Commas are not allowed. In C++ there are three types of floating-point constants: float- f or F 1.234f3 or 1.234F3 double - e or E 2.34e3 or 2.34E3 long double- l or L 0.123l5 or 0.123L5 Character Constant A Character enclosed in single quotation marks. E.g. : ‘A’, ‘n’
25
Constants Enumeration Provides a way for attaching names to numbers. E.g.: enum {X,Y,Z} ; The above example defines X,Y and Z as integer constants with values 0,1 and 2 respectively. Also can assign values to X, Y and Z explicitly. enum { X=100, Y=50, Z=200 };
26
Strings A String constant is a sequence of any of characters surrounded by double quotation marks. A String constant is a sequence of any number of characters surrounded by double quotation marks.E.g.: “This is a string constant.”
27
Punctuators Punctuators in C++ are used to delimit various syntactical units. The punctuators (also known as separators) in C++ include the following symbols: [ ] ( ) { }, ; : … * #
28
Operators Operators are tokens that result in some kind of computation or action when applied to variables or other elements in an expression. Some examples of operators are: ( ) ++ -- * / % + - > >= == != = += -= *= /= %= Operators act on operands. For example, CITY_RATE, gross_income are operands for the multiplication operator, *. An operator that requires one operand is a unary operator, one that requires two operands is binary, and an operator that acts on three operands is ternary.
29
Arithmetic Operators The basic arithmetic operators in C++ are the same as in most other computer languages. Following is a list of arithmetic operators in C++: Modulus Operator: a division operation where two integers are divided and the remainder is the result. E.g.:10 % 3 results in 1, 12 % 7 results in 5 and 20 % 5 results in 0. Integer Division: the result of an integer divided by an integer is always an integer (the remainder is truncated). E.g.:10/3 results in 3, 14/5 results in 2 and 1/2 results in 0. 1./2. or 1.0/2.0 results in 0.5 OperatorMeaning +Addition -Subtraction *Multiplication /Division %Modulus
30
Assignment Operators E.g.: x = x + 3;x + = 3; x = x - 3;x - = 3; x = x * 3;x * = 3; x = x / 3;x / = 3;
31
Increment & Decrement Operators Name of the operatorSyntaxResult Pre-increment++xIncrement x by 1 before use Post-incrementx++Increment x by 1 after use Pre-decrement--xDecrement x by 1 before use Post-decrementx--Decrement x by 1 before use E.g.: int x=10, y=0; y=++x;( x = 11, y = 11) y=x++; y=--x; y=x--; y=++x-3;y=x+++5;y=--x+2;y=x--+3;
32
Relational Operators Using relational operators we can direct the computer to compare two variables. Following is a list of relational operators: E.g.:if (thisNum < minimumSoFar) minimumSoFar = thisNum if (numberOfLegs != 8) thisBug = insect In C++ the truth value of these expressions are assigned numerical values: a truth value of false is assigned the numerical value zero and the value true is assigned a numerical value best described as not zero. OperatorMeaning >Greater than >=Greater than or equal to <Less than <=Less than or equal to ==Equal to !=Not equal to
33
Logical Operators Logical operators in C++, as with other computer languages, are used to evaluate expressions which may be true or false. Expressions which involve logical operations are evaluated and found to be one of two values: true or false. Examples of expressions which contain relational and logical operators if ((bodyTemp > 100) && (tongue == red)) status = flu; OperatorMeaningExample of useTruth Value &&AND(exp 1) && (exp 2)True if exp 1 and exp 2 are BOTH true. ||OR(exp 1) || (exp 2)True if EITHER (or BOTH) exp 1 or exp 2 are true. !NOT! (exp 1)Returns the opposite truth value of exp 1; if exp 1 is true, ! (exp 1) is false; if exp 1 is false, ! (exp 1) is true.
34
Operator Precedence Following table shows the precedence and associativity of all the C++ operators. (Groups are listed in order of decreasing precedence.) OperatorAssociativity ::left to right ->. ( ) [ ] postfix ++ postfix --left to right prefix ++ prefix -- ~ ! unary + unary – Unary * unary & (type) sizeof new delete right to left ->* *left to right * / %left to right + -left to right >left to right >=left to right == !=left to right & ^ |
35
Operator Precedence Contd… OperatorAssociativity &&left to right ||left to right ?:left to right = *= /= %= += -= >= &= ^= |= right to left,left to right
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.