Presentation is loading. Please wait.

Presentation is loading. Please wait.

OOP.

Similar presentations


Presentation on theme: "OOP."— Presentation transcript:

1 OOP

2 Contents of unit - I Introduction to procedural, modular, object-oriented and generic programming techniques Limitations of procedural programming Need of object-oriented programming Object Oriented Programming features Objects Classes & Class as ADT Data members Methods Message passing Data encapsulation Data abstraction Information hiding Inheritance(Code Reuse) Polymorphism(Function overloading and operator overloading)

3 Fundamentals of OO Programming
C++ Program Structure C++ Identifiers C++ Keywords Comments Primitive Built- in Types Variable declarations Local scope v/s Global Scope Literals Const keyword

4 Fundamentals of OO Programming(Continued)
Defining Function & Function Prototyping Function Declaration Function Calling Inline Function Pointers This pointer C++ References Standard INPUT & OUTPUT Streams Class Constructor & Destructor Static Keyword Static data members Static member function Dynamic memory Allocation & De-allocation New & Delete operator I/O manipulation

5 A Survey of Programming Techniques
Unstructured programming Procedural programming Modular programming Object-oriented programming Generic programming

6 Unstructured programming
Only one Program i.e. main Program All the sequences of commands or statements in one programs called main Program E.g. Fortran, assembly language, old Basic

7 Structured Programming
Also called as Procedural Programming For each task procedure is created The procedures are called from main

8 Modular programming Procedures with some common functionality are grouped together into separate modules Program is categorized into several smaller modules Each module can have its own data

9 Object-oriented programming
Works on objects which is considered smallest unit of the object oriented languages Focuses more on data rather than Procedures

10 Example Unstructured Programming:
#include #include void main() { int a,b,c; clrscr(); cout << "Enter the first number"; cin >> a; cout << "Enter the second number"; cin >> b; c=a+b; cout << "The sum is:" << c; getch(); }

11 Example #include #include
Procedural Programming: #include #include int add(int,int); void main() { int a,b,c; clrscr(); cout << "Enter the first number"; cin >> a; cout << "Enter the second number"; cin >> b; c=add(a,b); cout<<"The sum is:" << c; getch(); } int add(int x,int y) { int z=x+y; return z; }

12 Example Object Oriented programming #include #include class Addition { int a,b,c; public: void read() { cin >> a; cin >> b; } void add() { c=a+b; } void display() { cout << "The sum is:" << c; } }; void main() { Addition obj; //object creation cout << "Enter the numbers"; obj.read(); obj.add(); obj.display(); getch(); }

13 Limitations of procedural programming
Poor real world model. No importance to data. No privacy. No true reuse. Functions and data should be treated equally.

14 Procedural v/s object oriented programming

15 Procedure oriented Programming Object oriented Programming
Feature Procedure oriented Programming Object oriented Programming Divided Into In POP Program is divided into small parts called functions In OOP, program is divided into parts called objects. Importance In POP, Importance is not given to data but to functions as well as sequence of actions to be done. In OOP, Importance is given to the data rather than procedures or functions because it works as a real world. Approach POP follows Top Down approach. OOP follows Bottom Up approach Access Specifiers POP does not have any access specifier OOP has access specifiers named Public, Private, Protected, etc. Data Moving In POP, Data can move freely from function to function in the system. In OOP, objects can move and communicate with each other through member functions. Expansion To add new data and function in POP is not so easy. OOP provides an easy way to add new data and function Data Access In POP, Most function uses Global data for sharing that can be accessed freely from function to function in the system. In OOP, data can not move easily from function to function, it can be kept public or private so we can control the access of data. Data Hiding POP does not have any proper way for hiding data so it is less secure. OOP provides Data Hiding so provides more security. Overloading In POP, Overloading is not possible. In OOP, overloading is possible in the form of Function Overloading and Operator Overloading. Examples Example of POP are : C, VB, FORTRAN, Pascal. Example of OOP are : C++, JAVA, VB.NET, C#.NET.

16 GENERIC PROGRAMMING It is an idea that code should be as generic as possible Means writing templates e.g. container classes like arrays

17 Object oriented features

18 introduction C++ is a statically typed, compiled, general-purpose, case-sensitive, free-form programming language that supports procedural, object-oriented, and generic programming. C++ is regarded as a middle-level language, as it comprises a combination of both high-level and low-level language features Developed by Bjarne Stroustrup starting in at Bell Labs in Murray Hill, New Jersey

19 C++ Class Definition It is template, format or blueprint
Also can be said as user defined data Type A class definition starts with the keyword class followed by the class name; and the class body, enclosed by a pair of curly braces. Class definition must be followed by a semicolon Class contains data members and member function class Box{ public: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box };

20 Class as adt Abstract Data Types (ADTs)
type implementation & operations hidden implementation built-in and user-defined types are ADTs client ADT Implementation client Interface use client manufacturer’s responsibility

21 C++ Objects A class provides the blueprints for objects
an object is created from a class Object is variable of class type Objects are declared the same way the variables are declared Box Box1; // Declare Box1 of type Box Box Box2; // Declare Box2 of type Box Both of the objects Box1 and Box2 will have their own copy of data members.

22 Accessing the Data Members
The public data members of objects of a class can be accessed using the direct member access operator (.) #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 }; // box 2 specification Box2.height = 10.0; Box2.length = 12.0; Box2.breadth = 13.0; // volume of //box 1 volume = Box1.height * Box1.length * Box1.breadth; cout << "Volume of Box1 : " << volume <<endl;  // volume of box 2 volume = Box2.height * Box2.length * Box2.breadth; cout << "Volume of Box2 : " << volume <<endl; return 0;} 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.height = 5.0; Box1.length = 6.0; Box1.breadth = 7.0; 

23 Members of class A member function of a class is a function that has its definition or its prototype within the class Members are accessed using dot operator(.) class Box { public: double length; // Length of a box double breadth; // Breadth of a box data member double height; // Height of a box double getVolume(void); // Returns box volume // member function };

24 Members of class(continued…)
Member functions can be defined within the class definition or separately using scope resolution operator, :: 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; } };// class end

25 Members of class(continued…)
If you like you can define same function outside the class using scope resolution operator, :: as follows: double Box::getVolume(void){ return length * breadth * height; }

26 Data encapsulation The wrapping up of data and function into a single unit (called class) is known as encapsulation. Data and encapsulation is the most striking feature of a class. OOP encapsulates data (attributes) and functions (behavior) into packages called objects E.g. class encapsulates data members and member functions

27 Data abstraction Abstraction refers to the act of representing essential features without including the background details or explanation Classes use the concept of abstraction and are defined as a list of abstract attributes such as size, wait, and cost, and function operate on these attributes. E.g TV a television separates its internal implementation from its external interface and we can play with its interfaces like the power button, channel changer, and volume control without having any knowledge of its internals.

28 Information hiding Data hiding is one of the important features of Object Oriented Programming which allows preventing the functions of a program to access directly the internal representation of a class type The access restriction to the class members is specified by the labeled public, private, and protected sections within the class body private, and protected are called access specifiers/modifiers. A class can have multiple public, protected, or private labeled sections The default access for members and classes is private

29 Information hiding(continued)
class Base { public: // public members go here protected: // protected members go here private: // private members go here };

30 Information hiding(continued)
A public member is accessible from anywhere outside the class but within a program A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members. By default all the members of a class would be private A protected member variable or function is very similar to a private member but it provided one additional benefit that they can be accessed in child classes which are called derived classes

31 inheritance Inheritance is the process by which objects of one class acquired the properties of objects of another classes. In OOP, the concept of inheritance provides the idea of reusability add additional features to an existing class without modifying it

32 polymorphism Polymorphism is another important OOP concept. Polymorphism, a Greek term, means the ability to take more than on form An operation may exhibit different behavior is different instances. The process of making an operator to exhibit different behaviors in different instances is known as operator overloading. Using a single function name to perform different type of task is known as function overloading. E.g. abs(parameter type) instead of fabs(),labs(),abs()

33 Message passing An object-oriented program consists of a set of objects that communicate with each other. The process of programming in an object-oriented language, involves the following basic steps: Creating classes that define object and their behaviour, Creating objects from class definitions, and Establishing communication among objects. A Message for an object is a request for execution of a procedure, and therefore will invoke a function (procedure) in the receiving object that generates the desired results. Message passing involves specifying the name of object, the name of the function (message) and the information to be sent. Example:

34 Fundamentals of OO Programming

35 Use of C++ C++ is used by hundreds of thousands of programmers in essentially every application domain. C++ is being highly used to write device drivers and other softwares that rely on direct manipulation of hardware under real-time constraints. C++ is widely used for teaching and research because it is clean enough for successful teaching of basic concepts. Anyone who has used either an Apple Macintosh or a PC running Windows has indirectly used C++ because the primary user interfaces of these systems are written in C++.

36 C++ Program Structure #include <iostream>// headers using namespace std; // use std namespace // main() is where program execution begins. int main() { cout << "Hello World"; // prints Hello World// // statements return 0; }

37 C++ Identifier A C++ identifier is a name used to identify a variable, function, class, module, or any other user-defined item. Starts with a letter A to Z or a to z or an underscore (_) followed by zero or more letters, underscores, and digits (0 to 9). C++ does not allow punctuation characters such as @, $, and % within identifiers C++ is a case-sensitive programming language E.g. Mohd, zara, abc, move_name, a_123 myname50, _temp, j, a23b9, retVal

38

39 Comments Program comments are explanatory statements that you can include in the C++ code that you write and helps anyone reading it's source code All programming languages allow for some form of comments. C++ supports single-line and multi-line comments C++ comments start with /* and end with */. /* This is a comment */  /* C++ comments can also * span multiple lines */ // prints Hello World ---single line comment

40

41

42 Data type program #include <iostream> using namespace std;
int main(){ cout << "Size of char : " << sizeof(char) << endl; cout << "Size of int : " << sizeof(int) << endl; cout << "Size of short int : " << sizeof(short int) << endl; cout << "Size of long int : " << sizeof(long int) << endl; cout << "Size of float : " << sizeof(float) << endl; cout << "Size of double : " << sizeof(double) << endl; cout << "Size of wchar_t : " << sizeof(wchar_t) << endl; return 0; } // endl, which inserts a new-line character after every line

43 Variables Definition in C++
A variable definition means to tell the compiler where and how much to create the storage for the variable type variable_list; Example #include <iostream> using namespace std;  // Variable declaration: extern int a, b; extern int c; extern float f; int main (){ // Variable definition: int a, b, c; float f; // actual initialization a = 10; b = 20; c = a + b; cout << c << endl ;  f = 70.0/3.0; cout << f << endl ; return 0; }

44 variables In all programming languages, we need to use various variables to store various information are nothing but reserved memory locations to store values to store information of various data types like character, wide character, integer, floating point, double floating point, Boolean etc. Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Variable provides us with named storage that our programs can manipulate. The name of a variable can be composed of letters, digits, and the underscore character.

45 types of variable in C++
Description bool Stores either value true or false. char Typically a single octet(one byte). This is an integer type. int The most natural size of integer for the machine. float A single-precision floating point value. double A double-precision floating point value. void Represents the absence of type. wchar_t A wide character type.

46 local and global variables
Local Variable Variables that are declared inside a function or block are local variables. They can be used only by statements that are inside that function or block of code. Local variables are not known to functions outside their own #include <iostream> using namespace std; int main () { // Local variable declaration: int a, b; int c; // actual initialization a = 10; b = 20; c = a + b; cout << c; return 0; }

47 Global Variables Global variables are defined outside of all the functions, usually on top of the program The global variables will hold their value throughout the life-time of your program. A global variable can be accessed by any function Global variable is available for use throughout your entire program after its declaration

48 Global variables : example
#include <iostream> using namespace std; // Global variable declaration: int g = 20; int main () { // Local variable declaration: int g = 10; cout << g; return 0; }

49 literals Constants refer to fixed values that the program may not alter and they are called literals. Constants can be of any of the basic data types and can be divided into Integer Numerals, Floating- Point Numerals, Characters, Strings and Boolean Values. constants are treated just like regular variables except that their values cannot be modified after their definition

50 Integer literal An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for decimal. An integer literal can also have a suffix that is a combination of U and L, for unsigned and long, respectively. The suffix can be uppercase or lowercase and can be in any order

51 examples 212 // Legal 215u // Legal 0xFeeL // Legal 078 // Illegal: 8 is not an octal digit 032UU // Illegal: cannot repeat a suffix 85 // decimal 0213 // octal 0x4b // hexadecimal 30 // int 30u // unsigned int 30l // long 30ul // unsigned long

52 Floating point literals
A floating-point literal has an integer part, a decimal point, a fractional part, and an exponent part // Legal 314159E-5L // Legal 510E // Illegal: incomplete exponent 210f // Illegal: no decimal or exponent .e // Illegal: missing integer or fraction

53 Boolean literal There are two Boolean literals and they are part of standard C++ keywords: A value of true representing true. A value of false representing false

54 Character literals Character literals are enclosed in single quotes
If the literal begins with L (uppercase only), it is a wide character literal (e.g., L'x') and should be stored in wchar_t type of variable it is a narrow character literal (e.g., 'x') and can be stored in a simple variable of char type A character literal can be a plain character (e.g., 'x'), an escape sequence (e.g., '\t'), or a universal character (e.g., '\u02C0').

55 Escape sequences Escape sequence Meaning \\ \ character \' ' character
\" " character \? ? character \a Alert or bell \b Backspace \f Form feed \n Newline \r Carriage return \t Horizontal tab \v Vertical tab \ooo Octal number of one to three digits \xhh . . . Hexadecimal number of one or more digits

56 String literals String literals are enclosed in double quotes
A string contains characters that are similar to character literals: plain characters, escape sequences, and universal characters "hello, dear“ "hello, \ dear“ "hello, " "d" "ear"

57 Const keyword use const prefix to declare constants with a specific type as follows: const type variable = value; #include <iostream> using namespace std;  int main() { const int LENGTH = 10; const int WIDTH = 5; const char NEWLINE = '\n'; int area; area = LENGTH * WIDTH; cout << area; cout << NEWLINE; return 0; }

58 Defining a Function return_type function_name( parameter list ) {
body of the function } Return Type Function Name Parameters Function Body

59 Function Declarations
A function declaration tells the compiler about a function name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts: return_type function_name( parameter list ); int max(int num1, int num2); Function declaration is required when you define a function in one source file and you call that function in another file should declare the function at the top of the file calling the function.

60 Function calling While creating a C++ function, we give a definition of what the function has to do. To use a function, we will have to call or invoke that function. When a program calls a function, program control is transferred to the called function A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program Actual arguments and formal arguments

61 Function calling Call Type Description Call by value
This method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. Call by pointer This method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. Call by reference This method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.

62 pointer A pointer is a variable whose value is the address of another variable type *var-name; type is the pointer's base type it must be a valid C++ type and var-name is the name of the pointer variable. The asterisk we used to declare a pointer is the same asterisk that you use for multiplication int *ip; // pointer to an integer double *dp; // pointer to a double float *fp; // pointer to a float char *ch; // pointer to character

63 Using Pointers in C++ #include <iostream> using namespace std; int main () { int var = 20; // actual variable declaration. int *ip; // pointer variable ip = &var; // store address of var in pointer variable cout << "Value of var variable: "; cout << var << endl; // print the address stored in ip pointer variable cout << "Address stored in ip variable: "; cout << ip << endl; // access the value at the address available in pointer cout << "Value of *ip variable: "; cout << *ip << endl; return 0; }

64 output Value of var variable: 20
Address stored in ip variable: 0xbfc601ac Value of *ip variable: 20

65 C++ references Think of a variable name as a label attached to the variable's location in memory then think of a reference as a second label attached to that memory location int i = 17; int& r = i; Read the & in these declarations as reference

66 program #include <iostream> using namespace std; int main () { // declare simple variables int i; double d; // declare reference variables int &r = i; double & s = d; i = 5; cout << "Value of i : " << i << endl; cout << "Value of i reference : " << r << endl; d = 11.7; cout << "Value of d : " << d << endl; cout << "Value of d reference : " << s << endl; return 0; }

67 output Value of i : 5 Value of i reference : 5 Value of d : 11.7 Value of d reference : 11.7

68 C++ References v/s Pointers
References are often confused with pointers but three major differences between references and pointers are: We cannot have NULL references. We must always be able to assume that a reference is connected to a legitimate piece of storage. Once a reference is initialized to an object, it cannot be changed to refer to another object. Pointers can be pointed to another object at any time. A reference must be initialized when it is created. Pointers can be initialized at any time.

69 The standard input stream (cin)
The predefined object cin is an instance of istream class The cin object is said to be attached to the standard input device, which usually is the keyboard. The cin is used in conjunction with the stream extraction operator, which is written as >> which are two greater than signs int main( ) { char name[50]; cout << "Please enter your name: "; cin >> name; cout << "Your name is: " << name << endl; }

70 The standard input stream (cin)(cntd….)
The stream extraction operator >> may be used more than once in a single statement. To request more than one datum you can use the following: cin >> name >> age; This will be equivalent to the following two statements: cin >> name; cin >> age;

71 The standard output stream (cout)
The predefined object cout is an instance of ostream class The cout object is said to be "connected to" the standard output device, which usually is the display screen The cout is used in conjunction with the stream insertion operator, which is written as << which are two less than signs #include <iostream> using namespace std; int main( ) { char str[] = "Hello C++"; cout << "Value of str is : " << str << endl; }

72 The Class 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. 0-argument constructor Parameterized constructor

73 E.g. Class test_ctor{ private : int x,y; public : test_ctor(int x=0, int y=0){ this→x = x; this→ y=y; } tets_cot(){ //some code here…. void display(){ // some code goes here…..

74 Continued…. void main(){ test_ctor t1(10,20); tets_ctor t2; test_ctor t3; t3.display(); }

75 The Class Destructor A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class. A destructor will have exact same name as the class prefixed with a tilde (~) and it can neither return a value nor can it take any parameters. Destructor can be very useful for releasing resources before coming out of the program like closing files, releasing memories etc.

76 E.g.

77 Inline function C++ inline function is powerful concept that is commonly used with classes If a function is inline, the compiler places a copy of the code of that function at each point where the function is called at compile time. Any change to an inline function could require all clients of the function to be recompiled because compiler would need to replace all the code once again otherwise it will continue with old functionality. To inline a function, place the keyword inline before the function name and define the function before any calls are made to the function The compiler can ignore the inline qualifier in case defined function is more than a line.

78 Inline (cntd…) A function definition in a class definition is an inline function definition, even without the use of the inline specifier #include <iostream> using namespace std;  inline int Max(int x, int y) { return (x > y)? x : y; // Main function for the programint main( ) cout << "Max (20,10): " << Max(20,10) << endl; cout << "Max (0,200): " << Max(0,200) << endl; cout << "Max (100,1010): " << Max(100,1010) << endl; return 0; }

79 output Max (20,10): 20 Max (0,200): 200 Max (100,1010): 1010

80 Static keyword We can define class members static using static keyword
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. A static member is shared by all objects of the class All static data is initialized to zero when the first object is created, if no other initialization is present

81 #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; 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;

82 output Constructor called. Total objects: 2

83 Static Function Members
By declaring a function member as static, we 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. Program during labs.

84 Dynamic memory allocation and de-allocation
Memory in your C++ program is divided into two parts The stack: All variables declared inside the function will take up memory from the stack → Static memory allocation The heap: This is unused memory of the program and can be used to allocate the memory dynamically when program runs. → Dynamic memory allocation Many times, we are not aware in advance how much memory we will need to store particular information in a defined variable and the size of required memory can be determined at run time

85 Dynamic memory allocation and de-allocation(cntd….)
In static memory allocation, decision of memory allocation is done at compile time e.g. int a; During run time variables are created In dynamic allocation both decision & allocation of memory is done during execution time.

86 New and delete operator
We can allocate memory at run time within the heap for the variable of a given type using a special operator in C++ which returns the address of the space allocated. This operator is called new operator. Use delete operator, which de-allocates memory previously allocated by new operator. Syntax : new data-type; data-type could be any built-in data type

87 E.g. #include<iostream> using namespace std; int main() { int n, *pointer,c; cout<<“enter an integer\n”; cin>>n; pointer = new int[n]; cout<<“enter”<<n<<“ integers\n”; for(c=0;c<n;c++) cin>>pointer[c]; cout<<“elements entered by you are\n”; for(c=0;c<n;c++) cout<<poineter[c]<<endl; delete[] pointer; return 0; }

88 New operator void main(){ int x, float y, int *p; p = new int; }
Now compiler makes an entry in symbol table new allocates memory, calls constructor New creates nameless objects. what is allocated must be de-allocated so use delete operator which calls destructor, de-allocates memory.

89 Named & nameless objects....!!!
class shape{ private : int a,b; }; shape p; → name object created (p) Shape *q; q = new shape; → name less object created.

90 E.g. New and delete operator
Class example { private : int i, float a; public : example(){ i=0; a=0.0; } Example(int ii, float aa){ i = ii; a= aa; }; void main(){ example *p1,*p2; p1 = new example; p2 = new example(15,30.5); delete p1; delete p2; }

91 This pointer Also called as constant pointer
“this” keyword is used to identify between local and instance variables

92 Class this_test{ private : int i, float a; public : void setdata(int i, float a){ this→i = i; this→ a= a; } }; void main(){ this_test t1,t2; t1.setdata(10,20.5);

93 Formatting flags and manipulators
The following output manipulators control the format of the output stream Include <iomanip> The Range column tells how long the manipulator will take effect: now inserts something at that point, next affects only the next data element, and all affects all subsequent data elements for the output stream.

94 references Let us c++ by yashwant kaetkar
Object oriented programming with c++ by balagurusamy cpp/index.html tors/


Download ppt "OOP."

Similar presentations


Ads by Google