Object Oriented Programming with C++ Diploma in Computer System Design.

35
Object Oriented Object Oriented Programming with Programming with C++ C++ Diploma in Computer System Diploma in Computer System Design Design

Transcript of Object Oriented Programming with C++ Diploma in Computer System Design.

Page 1: Object Oriented Programming with C++ Diploma in Computer System Design.

Object Oriented Object Oriented Programming with C++Programming with C++

Diploma in Computer System DesignDiploma in Computer System Design

Page 2: Object Oriented Programming with C++ Diploma in Computer System Design.

Course OutlineCourse OutlineChapter 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

Page 3: Object Oriented Programming with C++ Diploma in Computer System Design.

Chapter 2 Chapter 2 Introduction to C++Introduction to C++

What is C++

A Simple C++ program

Structure of a C++ program

Tokens

Data Types

Expressions

Control Structures

Page 4: Object Oriented Programming with C++ Diploma in Computer System Design.

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++What is C++

Page 5: Object Oriented Programming with C++ Diploma in Computer System Design.

A Simple C++ program A Simple C++ program 1 // example1.cpp

2 // Displaying a String.

3 #include <iostream.h> // include header file

4 int main()5 {6 cout << “C++ is better C.”; // C++ statement 7 return 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.

Page 6: Object Oriented Programming with C++ Diploma in Computer System Design.

Comments 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.

*/

Page 7: Object Oriented Programming with C++ Diploma in Computer System Design.

The iostream.h FileThe 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 <iostream.h> // include header file

Page 8: Object Oriented Programming with C++ Diploma in Computer System Design.

Output OperatorOutput 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.

6 cout << “C++ is better C.”; // C++ statement

Page 9: Object Oriented Programming with C++ Diploma in Computer System Design.

Input Operator Input Operator 1 // example2.cpp

2 // Input two numbers.

3 #include <iostream.h> // include header file

4 int main()5 {6 float number1, number2;7 cout << “Enter two numbers separated by a space : ”; 8 cin >> number1;9 cin >> number2;10 return 0;11 }12 // End of example

Enter two numbers separated by a space : 2.5 6.7

Page 10: Object Oriented Programming with C++ Diploma in Computer System Design.

Input Operator 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.

Page 11: Object Oriented Programming with C++ Diploma in Computer System Design.

Cascading I/O Operator Cascading I/O Operator 1 // example3.cpp

2 // Input two numbers and display them.

3 #include <iostream.h> // include header file

4 int main()5 {6 float number1, number2;7 cout << endl;8 cout << “Enter two numbers separated by a space : ”; 9 cin >> number1 >> number2;10 cout << “Number1 : ” << number1 << “\n” << “Number2 : ” << number2;11 return 0;12 }13 // End of exampleEnter two numbers separated by a space : 2.5 6.7Number1 : 2.5Number2 : 6.7

Page 12: Object Oriented Programming with C++ Diploma in Computer System Design.

Return StatementReturn 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.

Page 13: Object Oriented Programming with C++ Diploma in Computer System Design.

An example with Class An example with Class 1 // example4.cpp

2 // A Class example.

3 #include <iostream.h> // include header file

4 class person // new data type 5 {6 char 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 {15 cout << endl;16 cout << “Enter name : ”; cin >> name;17 cout << “Enter age : ”; cin >> age;18 }

Page 14: Object Oriented Programming with C++ Diploma in Computer System Design.

An example with Class contd…An example with Class contd…19 void person : : display(void) // member function

20 {21 cout << “\nName : ” << name;22 cout << “\nAge : ” << age;23 }24 25 int main()26 {27 person p; // object of type person

28 p.getdata();29 p.display();30 return 0;31 }

Enter name : LalithEnter age : 24

Name : LalithAge : 24

Page 15: Object Oriented Programming with C++ Diploma in Computer System Design.

An example with Class contd…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.

Page 16: Object Oriented Programming with C++ Diploma in Computer System Design.

Structure of a C++ ProgramStructure 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.

Page 17: Object Oriented Programming with C++ Diploma in Computer System Design.

Structure of a C++ ProgramStructure 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).

Page 18: Object Oriented Programming with C++ Diploma in Computer System Design.

Creating the Source FileCreating 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.

Page 19: Object Oriented Programming with C++ Diploma in Computer System Design.

Review Questions & ExercisesReview 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 << “Enter value:”; cin >> 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

Page 20: Object Oriented Programming with C++ Diploma in Computer System Design.

TokensTokensA 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

Page 21: Object Oriented Programming with C++ Diploma in Computer System Design.

KeywordsKeywordsImplements 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++:

asmasm deletedelete ifif returnreturn trytry

autoauto dodo inlineinline shortshort typedeftypedef

breakbreak doubledouble intint signedsigned unionunion

casecase elseelse longlong sizeofsizeof unsignedunsigned

catchcatch enumenum newnew staticstatic virtualvirtual

charchar externextern operatoroperator structstruct voidvoid

classclass floatfloat privateprivate switchswitch volatilevolatile

constconst forfor protectedprotected templatetemplate whilewhile

continuecontinue friendfriend publicpublic thisthis

defaultdefault gotogoto registerregister throwthrow

Page 22: Object Oriented Programming with C++ Diploma in Computer System Design.

IdentifiersIdentifiersIdentifiers 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.

Page 23: Object Oriented Programming with C++ Diploma in Computer System Design.

ConstantsConstantsConstants 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;

Page 24: Object Oriented Programming with C++ Diploma in Computer System Design.

ConstantsConstantsFloating-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’

Page 25: Object Oriented Programming with C++ Diploma in Computer System Design.

ConstantsConstantsEnumeration

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 };

Page 26: Object Oriented Programming with C++ Diploma in Computer System Design.

StringsStringsA String constant is a sequence of any A String constant is a sequence of any number of characters of characters surrounded by double quotation marks.surrounded by double quotation marks.

E.g.: E.g.:

““This is a string constant.”This is a string constant.”

Page 27: Object Oriented Programming with C++ Diploma in Computer System Design.

PunctuatorsPunctuatorsPunctuators in C++ are used to delimit various syntactical units.

The punctuators (also known as separators) in C++ include the following symbols:

[ ] ( ) { } , ; : … * #

Page 28: Object Oriented Programming with C++ Diploma in Computer System Design.

OperatorsOperatorsOperators 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.

Page 29: Object Oriented Programming with C++ Diploma in Computer System Design.

Arithmetic OperatorsArithmetic OperatorsThe 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

OperatorOperator MeaningMeaning

++ AdditionAddition

-- SubtractionSubtraction

** MultiplicationMultiplication

// DivisionDivision

%% ModulusModulus

Page 30: Object Oriented Programming with C++ Diploma in Computer System Design.

Assignment OperatorsAssignment OperatorsE.g.:

x = x + 3; x + = 3;

x = x - 3; x - = 3;

x = x * 3; x * = 3;

x = x / 3; x / = 3;

Page 31: Object Oriented Programming with C++ Diploma in Computer System Design.

Increment & Decrement OperatorsIncrement & Decrement OperatorsName of the operator Syntax Result

Pre-increment ++x Increment x by 1 before use

Post-increment x++ Increment x by 1 after use

Pre-decrement --x Decrement x by 1 before use

Post-decrement x-- 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;

Page 32: Object Oriented Programming with C++ Diploma in Computer System Design.

Relational OperatorsRelational OperatorsUsing 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.

OperatorOperator MeaningMeaning

> Greater than

>= Greater than or equal to

< Less than

<= Less than or equal to

== Equal to

!= Not equal to

Page 33: Object Oriented Programming with C++ Diploma in Computer System Design.

Logical OperatorsLogical OperatorsLogical 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;

Operator Meaning Example of use Truth 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.

Page 34: Object Oriented Programming with C++ Diploma in Computer System Design.

Operator PrecedenceOperator PrecedenceFollowing table shows the precedence and associativity of all the C++ operators. (Groups are listed in order of decreasing precedence.)

Operator Associativity

:: 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

& left to right

^ left to right

| left to right

Page 35: Object Oriented Programming with C++ Diploma in Computer System Design.

Operator Precedence Contd…Operator Precedence Contd…

Operator Associativity

&& left to right

|| left to right

?: left to right

= *= /= %= += -=

<<= >>= &= ^= |=

right to left

, left to right