Presentation is loading. Please wait.

Presentation is loading. Please wait.

Object Oriented Programming using c++ Submitted by :- MADHU MADHAN Lecturer in Computer Engg. G .P. MEHAM (ROHTAK)

Similar presentations


Presentation on theme: "Object Oriented Programming using c++ Submitted by :- MADHU MADHAN Lecturer in Computer Engg. G .P. MEHAM (ROHTAK)"— Presentation transcript:

1 Object Oriented Programming using c++ Submitted by :- MADHU MADHAN Lecturer in Computer Engg. G .P. MEHAM (ROHTAK)

2 Concept of Class and Object
“Class” refers to a blueprint. It defines the variables and methods the objects support “Object” is an instance of a class. Each object has a class which defines its data and behavior

3 Class Members A class can have three kinds of members:
fields: data variables which determine the status of the class or an object methods: executable code of the class built from statements. It allows us to manipulate/change the status of an object or access the value of the data member nested classes and nested interfaces

4 Sample class class Pencil { public String color = “red”;
public int length; public float diameter; public static long nextID = 0; public void setColor (String newColor) { color = newColor; }

5 Classes and Objects

6 const (Constant) Objects and const Member Functions
Principle of least privilege Only give objects permissions they need, no more Keyword const Specify that an object is not modifiable Any attempt to modify the object is a syntax error Example const Time noon( 12, 0, 0 ); Declares a const object noon of class Time and initializes it to 12

7 const (Constant) Objects and const Member Functions
const objects require const functions Member functions declared const cannot modify their object const must be specified in function prototype and definition Prototype: ReturnType FunctionName(param1,param2…) const; Definition: ReturnType FunctionName(param1,param2…) const { …} Example: int A::getValue() const { return privateDataMember }; Returns the value of a data member but doesn’t modify anything so is declared const Constructors / Destructors cannot be const They need to initialize variables, therefore modifying them

8 1 // Fig. 7.1: time5.h 2 // Declaration of the class Time. 3 // Member functions defined in time5.cpp 4 #ifndef TIME5_H 5 #define TIME5_H 6 7 class Time { 8 public: 9 Time( int = 0, int = 0, int = 0 ); // default constructor 10 11 // set functions 12 void setTime( int, int, int ); // set time 13 void setHour( int ); // set hour 14 void setMinute( int ); // set minute 15 void setSecond( int ); // set second 16 17 // get functions (normally declared const) 18 int getHour() const; // return hour 19 int getMinute() const; // return minute 20 int getSecond() const; // return second 21 22 // print functions (normally declared const) 23 void printMilitary() const; // print military time 24 void printStandard(); // print standard time 25 private: 26 int hour; // 27 int minute; // 28 int second; // 29 }; 30 31 #endif

9 The constructor is non-const but it can be called for const objects.
32 // Fig. 7.1: time5.cpp 33 // Member function definitions for Time class. 34 #include <iostream> 35 36 using std::cout; 37 38 #include "time5.h" 39 40 // Constructor function to initialize private data. 41 // Default values are 0 (see class definition). 42 Time::Time( int hr, int min, int sec ) 43 { setTime( hr, min, sec ); } 44 45 // Set the values of hour, minute, and second. 46 void Time::setTime( int h, int m, int s ) 47 { 48 setHour( h ); 49 setMinute( m ); 50 setSecond( s ); 51 } 52 53 // Set the hour value 54 void Time::setHour( int h ) 55 { hour = ( h >= 0 && h < 24 ) ? h : 0; } 56 57 // Set the minute value 58 void Time::setMinute( int m ) 59 { minute = ( m >= 0 && m < 60 ) ? m : 0; } 60 61 // Set the second value 62 void Time::setSecond( int s ) 63 { second = ( s >= 0 && s < 60 ) ? s : 0; } The constructor is non-const but it can be called for const objects.

10 64 65 // Get the hour value 66 int Time::getHour() const { return hour; } 67 68 // Get the minute value 69 int Time::getMinute() const { return minute; } 70 71 // Get the second value 72 int Time::getSecond() const { return second; } 73 74 // Display military format time: HH:MM 75 void Time::printMilitary() const 76 { 77 cout << ( hour < 10 ? "0" : "" ) << hour << ":" << ( minute < 10 ? "0" : "" ) << minute; 79 } 80 81 // Display standard format time: HH:MM:SS AM (or PM) 82 void Time::printStandard() // should be const 83 { 84 cout << ( ( hour == 12 ) ? 12 : hour % 12 ) << ":" << ( minute < 10 ? "0" : "" ) << minute << ":" << ( second < 10 ? "0" : "" ) << second << ( hour < 12 ? " AM" : " PM" ); 88 } Non-const functions cannot use const objects, even if they don’t modify them (such as printStandard).

11 89 // Fig. 7.1: fig07_01.cpp 90 // Attempting to access a const object with 91 // non-const member functions. 92 #include "time5.h" 93 94 int main() 95 { 96 Time wakeUp( 6, 45, 0 ); // non-constant object 97 const Time noon( 12, 0, 0 ); // constant object 98 // MEMBER FUNCTION OBJECT wakeUp.setHour( 18 ); // non-const non-const 101 noon.setHour( 12 ); // non-const const 103 wakeUp.getHour(); // const non-const 105 noon.getMinute(); // const const noon.printMilitary(); // const const noon.printStandard(); // non-const const return 0; 110 } Compiling... Fig07_01.cpp d:fig07_01.cpp(14) : error C2662: 'setHour' : cannot convert 'this' pointer from 'const class Time' to 'class Time &' Conversion loses qualifiers d:\fig07_01.cpp(20) : error C2662: 'printStandard' : cannot convert 'this' pointer from 'const class Time' to 'class Time &' Time5.cpp Error executing cl.exe. test.exe - 2 error(s), 0 warning(s)

12 const (Constant) Objects and const Member Functions
Member initializer syntax Data member increment in class Increment constructor for Increment is modified as follows: Increment::Increment( int c, int i ) : increment( i ) { count = c; } : increment( i ) initializes increment to i All data members can be initialized using member initializer syntax consts and references must be initialized using member initializer syntax Multiple member initializers Use comma-separated list after the colon

13 1 // Fig. 7.2: fig07_02.cpp 2 // Using a member initializer to initialize a 3 // constant of a built-in data type. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 class Increment { 10 public: 11 Increment( int c = 0, int i = 1 ); 12 void addIncrement() { count += increment; } 13 void print() const; 14 15 private: 16 int count; 17 const int increment; // const data member 18 }; 19 20 // Constructor for class Increment 21 Increment::Increment( int c, int i ) 22 : increment( i ) // initializer for const member 23 { count = c; } 24 25 // Print the data 26 void Increment::print() const 27 { 28 cout << "count = " << count << ", increment = " << increment << endl; 30 } 31 32 int main() 33 { If we try to initialize increment with an assignment statement (such as increment = i ) instead of a member initializer we get an error.

14 34 Increment value( 10, 5 ); 35 36 cout << "Before incrementing: "; 37 value.print(); 38 39 for ( int j = 0; j < 3; j++ ) { value.addIncrement(); cout << "After increment " << j + 1 << ": "; value.print(); 43 } 44 45 return 0; 46 } Before incrementing: count = 10, increment = 5 After increment 1: count = 15, increment = 5 After increment 2: count = 20, increment = 5 After increment 3: count = 25, increment = 5

15 Objects as Members of Classes
Construction of objects Member objects constructed in order declared Not in order of constructor’s member initializer list Constructed before their enclosing class objects (host objects)

16 friend Functions and friend Classes
friend function and friend classes Can access private and protected members of another class friend functions are not member functions of class Defined outside of class scope Properties of friendship Friendship is granted, not taken Not symmetric (if B a friend of A, A not necessarily a friend of B) Not transitive (if A a friend of B, B a friend of C, A not necessarily a friend of C)

17 friend Functions and friend Classes
friend declarations To declare a friend function Type friend before the function prototype in the class that is giving friendship friend int myFunction( int x ); should appear in the class giving friendship To declare a friend class Type friend class Classname in the class that is giving friendship if ClassOne is granting friendship to ClassTwo, friend class ClassTwo; should appear in ClassOne's definition

18 Changing private variables allowed.
1 // Fig. 7.5: fig07_05.cpp 2 // Friends can access private members of a class. 3 #include <iostream> 4 5 using std::cout; 6 using std::endl; 7 8 // Modified Count class 9 class Count { 10 friend void setX( Count &, int ); // friend declaration 11 public: 12 Count() { x = 0; } // constructor 13 void print() const { cout << x << endl; } // output 14 private: 15 int x; // data member 16 }; 17 18 // Can modify private data of Count because 19 // setX is declared as a friend function of Count 20 void setX( Count &c, int val ) 21 { 22 c.x = val; // legal: setX is a friend of Count 23 } 24 25 int main() 26 { 27 Count counter; 28 29 cout << "counter.x after instantiation: "; 30 counter.print(); Changing private variables allowed.

19 31 cout << "counter.x after call to setX friend function: ";
32 setX( counter, 8 ); // set x with a friend 33 counter.print(); 34 return 0; 35 } counter.x after instantiation: 0 counter.x after call to setX friend function: 8

20 1 // Fig. 7.6: fig07_06.cpp 2 // Non-friend/non-member functions cannot access 3 // private data of a class. 4 #include <iostream> 5 6 using std::cout; 7 using std::endl; 8 9 // Modified Count class 10 class Count { 11 public: 12 Count() { x = 0; } // constructor 13 void print() const { cout << x << endl; } // output 14 private: 15 int x; // data member 16 }; 17 18 // Function tries to modify private data of Count, 19 // but cannot because it is not a friend of Count. 20 void cannotSetX( Count &c, int val ) 21 { 22 c.x = val; // ERROR: 'Count::x' is not accessible 23 } 24 25 int main() 26 { 27 Count counter; 28 29 cannotSetX( counter, 3 ); // cannotSetX is not a friend 30 return 0; 31 }

21 Program Output Compiling... Fig07_06.cpp
Compiling... Fig07_06.cpp D:\books\2000\cpphtp3\examples\Ch07\Fig07_06\Fig07_06.cpp(22) : error C2248: 'x' : cannot access private member declared in class 'Count' D:\books\2000\cpphtp3\examples\Ch07\Fig07_06\ Fig07_06.cpp(15) : see declaration of 'x' Error executing cl.exe. test.exe - 1 error(s), 0 warning(s) Program Output

22 Dynamic Memory Allocation with Operators new and delete
Used for dynamic memory allocation Superior to C’s malloc and free new Creates an object of the proper size, calls its constructor and returns a pointer of the correct type delete Destroys object and frees space Examples of new TypeName *typeNamePtr; Creates pointer to a TypeName object typeNamePtr = new TypeName; new creates TypeName object, returns pointer (which typeNamePtr is set equal to)

23 Dynamic Memory Allocation with Operators new and delete
Examples of delete delete typeNamePtr; Calls destructor for TypeName object and frees memory Delete [] arrayPtr; Used to dynamically delete an array Initializing objects double *thingPtr = new double( ); Initializes object of type double to int *arrayPtr = new int[ 10 ]; Creates a ten element int array and assigns it to arrayPtr

24 static Class Members static class members
Shared by all objects of a class Normally, each object gets its own copy of each variable Efficient when a single copy of data is enough Only the static variable has to be updated May seem like global variables, but have class scope only accessible to objects of same class Initialized at file scope Exist even if no instances (objects) of the class exist Both variables and functions can be static Can be public, private or protected

25 static Class Members static variables
Static variables are accessible through any object of the class public static variables Can also be accessed using scope resolution operator(::) Employee::count private static variables When no class member objects exist, can only be accessed via a public static member function To call a public static member function combine the class name, the :: operator and the function name Employee::getCount()

26 static Class Members Static functions
static member functions cannot access non-static data or functions There is no this pointer for static functions, they exist independent of objects

27 Data Types

28 Objectives of this session
Keywords Identifiers Basic Data Types Built-in Data Types User-defined Data Types Derived Data Types

29 Variables and Data Types
Tokens The smallest individual units in a program are known as tokens. Keywords Identifiers Constants Strings Operators

30 Keywords

31 Identifiers A valid identifier is a sequence of one or more letters, digits or underscore characters (_). Neither spaces nor punctuation marks or symbols can be part of an identifier. Only letters, digits and single underscore characters are valid. In addition, variable identifiers always have to begin with a letter. They can also begin with an underline character (_ ).

32 Identifiers The name of a variable:
continue… The name of a variable: Starts with an underscore “_” or a letter, lowercase or uppercase, such as a letter from a to z or from A to Z. Examples are Name, gender, _Students, pRice. Can include letters, underscore, or digits. Examples are: keyboard, Master, Junction, Player1, total_grade, _ScoreSide1. Cannot include special characters such as !, %, ], or $. Cannot include an empty space. Cannot be any of the reserved words. Should not be longer than 32 characters (although allowed).

33 Basic Data Types C++ Data Types User-defined Type Built-in Type
Derived Type structure union class enumeration array function pointer reference Integral Type Void Floating Type int char float double

34 Built-in Data Types int, char, float, double are known as basic or fundamental data types. Signed, unsigned, long, short modifier for integer and character basic data types. Long modifier for double.

35 Built-in Data Types Type void was introduced in ANSI C.
continue… Type void was introduced in ANSI C. Two normal use of void: To specify the return type of a function when it is not returning any value. To indicate an empty argument list to a function. eg:- void function-name ( void )

36 Built-in Data Types continue… Type void can also used for declaring generic pointer. A generic pointer can be assigned a pointer value of any basic data type, but it may not be de-referenced. void *gp; // gp becomes generic pointer int *ip; // int pointer gp = ip; // assign int pointer to void pointer Assigning any pointer type to a void pointer is allowed in C & C++.

37 Built-in Data Types continue… void *gp; // gp becomes generic pointer int *ip; // int pointer ip = gp; // assign void pointer to int pointer This is allowed in C. But in C++ we need to use a cast operator to assign a void pointer to other type pointers. ip = ( int * ) gp; // assign void pointer to int pointer // using cast operator *ip = *gp;  is illegal

38 User-Defined Data Types
continue… Enumerated Data Type: Enumerated data type provides a way for attaching names to numbers. enum keyword automatically enumerates a list of words by assigning them values 0, 1, 2, and so on. enum shape {circle, square, triangle}; enum colour {red, blue, green, yellow}; enum position {off, on};

39 User-Defined Data Types
continue… Enumerated Data Type: enum colour {red, blue, green, yellow}; In C++ the tag names can be used to declare new variables. colour background; In C++ each enumerated data type retains its own separate type. C++ does not permit an int value to be automatically converted to an enum value.

40 User-Defined Data Types
continue… Enumerated Data Type: colour background = blue; // allowed colour background = 3; // error in C++ colour background = (colour) 3; // OK int c = red; // valid

41 User-Defined Data Types
continue… Enumerated Data Type: By default, the enumerators are assigned integer values starting with 0. We can override the default value by explicitly assigning integer values to the enumerators. enum colour { red, blue=4, green =8}; enum colour {red=5, blue, green};

42 User-Defined Data Types
continue… Enumerated Data Type: C++ also permits the creation of anonymous enum (i.e., enum with out tag name). enum {off, on}; here off  0 and on  1 int switch_1 = off; int switch_2 = on;

43 Derived Data Types Arrays Functions
The application of arrays in C++ is similar to that in C. Functions top-down - structured programming ; to reduce length of the program ; reusability ; function over-loading.

44 Derived Data Types Pointers
continue… Pointers Pointers can be declared and initialized as in C. int * ip; // int pointer ip = &x; // address of x assigned to ip *ip = 10; // 10 assigned to x through indirection

45 Derived Data Types Pointers
continue… Pointers C++ adds the concept of constant pointer and pointer to a constant. char * const ptr1 = “GOODS”; // constant pointer int const * ptr2 = &m; // pointer to a constant

46 Computer Fundamentals and Programming in C
OPERATORS Computer Fundamentals and Programming in C

47 Operators and Expressions
An operator is a symbol or letter used to indicate a specific operation on variables in a program. Example, the symbol `+' is an add operator that adds two data items called operands. Expression. An expression is a combination of operands (i.e., constants, variables, numbers) connected by operators and parentheses. Example, in the expression given below, A and B are operands and `+' is an operator. A + B An expression that involves arithmetic operators is known as an arithmetic expression. The computed result of an arithmetic expression is always a numerical value. An expression which involves relational and/or logical operators is called a Boolean expression or logical expression. The computed result of such an expression is a logical value, i.e., either 1 (True) or 0 (False). Computer Fundamentals and Programming in C

48 Rules for Formation of an Expression
A signed or unsigned constant or variable is an expression. An expression connected by an operator to a variable or a constant is an expression. Two expressions connected by an operator also form an expression. Two operators should not occur in continuation. Computer Fundamentals and Programming in C

49 Computer Fundamentals and Programming in C
Arithmetic Operators Arithmetic operators can further be classified as unary operators and binary operators. Arithmetic operators Computer Fundamentals and Programming in C

50 Binary Arithmetic Operators
The binary arithmetic operators supported by C are addition, subtraction, multiplication, division, and modulus or remainder. They are called binary operators because they require two operands to work with. The evaluations of binary operators is left associative. Operators of the same level are evaluated from left to right. Computer Fundamentals and Programming in C

51 Unary Arithmetic Operators
A unary operator requires only one operand or data item. The unary arithmetic operators supported by C are, unary minus (‘–’), increment (‘++’), and decrement (‘––’). Compared to binary operators, the unary operators are right associative in the sense that they evaluate from right to left. The operators ‘++’ and ‘––’ are unique to C. These are called increment and decrement operators respectively. The increment operator ++ adds 1 to its operand. Therefore we can say that the following expressions are equivalent.  i = i +1 ; ≡ ++i Computer Fundamentals and Programming in C

52 Arithmetic with Characters
A peculiar aspect of C is that arithmetic operations can also be performed with characters as shown in the following program segment. : char ch; ch = `A'; ch = ch + 1; printf ("ch = % c", ch); The output of this program segment would be: ch = B Computer Fundamentals and Programming in C

53 Computer Fundamentals and Programming in C
Key Points The division of an integer by another integer always results in an integer value. Example: the result of 5/2 is 2 (the decimal portion of the result is dropped). If both or one of the operands in a division operation is a floating point, the result is always a floating point. Example: the result of 15/2.0 is 7.5. The remainder operator % produces the remainder of an integer division. For example, the result of 5 % 2 is 1. This operator cannot be used with floating point numbers. Computer Fundamentals and Programming in C

54 Relational and Logical Operators
A relational operator is used to compare two values and the result of such an operation is always logical, i.e., either true or false. The valid relational operators supported by C are given below: Symbol Stands for Example >= <= == != Greater than Greater than equal to Less than Less than equal to Equal to Not equal to X > Y X >= Y X < Y X <= Y X == Y X != Y Computer Fundamentals and Programming in C

55 Computer Fundamentals and Programming in C
Logical Operators A logical operator is used to connect two relational expressions or logical expressions. The result of such an operation is always logical, i.e., either True (1) or False (0). The valid logical operators supported by C are given below: Symbol Stands for Example && || ! Logical AND Logical OR Logical NOT x && y x || y ! x Computer Fundamentals and Programming in C

56 Rules of Logical Operators
The output of a logical AND operation is true if both its operands are true. For all other combinations, the result is false. The output of a logical OR operation is false if both of its operands are false. For all other combinations the result is true. The logical NOT is a unary operator. It negates the value of the operand. Computer Fundamentals and Programming in C

57 Computer Fundamentals and Programming in C
Assignment Statement An assignment statement assigns the value of the expression on the right hand side to a variable on the left hand side of the assignment operator (=). Its general form is given below: < variable name > = < expression > The variable on the left side of the assignment operator is also called lvalue and is an accessible address in the memory. Expressions and constants on the right side of the assignment operator are called rvalues. Multiple assignments in a single statement can be used, especially when the same value is to be assigned to a number of variables. a = b = c = 30; A point worth noting is that C converts the type of the value on the right hand side to the data type on the left. Computer Fundamentals and Programming in C

58 FILES

59 Files Programs and data are stored on disk in structures called files
Examples Turbo C++ - binary file Word binary file lab1.c - text file lab1.data - text file term-paper - text file

60 Text Files All files are coded as long sequences of bits (0s and 1s)
Some files are coded as sequences of ASCII character values (referred to as text files) files are organized as bytes, with each byte being an ASCII character Other files are generally referred to as binary files

61 File Terms Buffer - a temporary storage area used to transfer data back and forth between memory and auxiliary storage devices Stream - files are manipulated in C with streams, a stream is a mechanism that is connected to a file that allows you to access one element at a time

62 File Pointers Each stream in C is manipulated with the file pointer type FILE *stream FILE is a type containing multiple parts file for stream, current element in file, etc. FILE * is the address where the FILE type is located in memory FILEs always manipulated as FILE *

63 Standard File Pointers
<stdio.h> contains three standard file pointers that are created for you (each of type FILE *) stdin - file pointer connected to the keyboard stdout - file pointer connected to the output window/terminal stderr - file pointer connected to the error window (generally the output window)/terminal

64 Showing a File FILE *ins; int c; if ((ins = fopen(“file1”,”r”)) == NULL) { printf(“Unable to open file1\n”); exit(0); } while ((c = fgetc(ins)) != EOF) putchar(c); fclose(ins);

65 Writing Characters C also provides functions for writing one character: int putchar(int c) - prints char c to output window int putc(int c, FILE *fp) - print char c to stream fp int fputc(int c, FILE *fp) - print c to stream fp Routines accept int args (chars are coerced) Routines return EOF if there is a problem

66 Creating a File FILE *outs; int c; if ((outs = fopen(“file2”,”w”)) == NULL) { printf(“Unable to open file2\n”); exit(0); } while ((c = getchar()) != EOF) fputc(c,outs); fclose(outs);

67 Copying a File FILE *ins; FILE *outs; int c; if ((ins = fopen(“file1”,”r”)) == NULL) { printf(“Unable to open file1\n”); exit(0); } if ((outs = fopen(“file2”,”w”)) == NULL) { printf(“Unable to open file2\n”); while ((c = fgetc(ins)) != EOF) fputc(c,outs); fclose(ins); fclose(outs);

68 THANK YOU


Download ppt "Object Oriented Programming using c++ Submitted by :- MADHU MADHAN Lecturer in Computer Engg. G .P. MEHAM (ROHTAK)"

Similar presentations


Ads by Google