Presentation is loading. Please wait.

Presentation is loading. Please wait.

Subject Name: Object Oriented Programming with C++

Similar presentations


Presentation on theme: "Subject Name: Object Oriented Programming with C++"— Presentation transcript:

1 Subject Name: Object Oriented Programming with C++
Subject Code: 10CS36 Prepared By: Tamilarasi, Deepa , Madhuleena, Neema Department: CSE Date : 11/11/2018

2 Classes & Objects

3 Procedure Oriented Programming (POP)
In POP, a problem is viewed as a sequence of things to be done such as reading, calculating and printing. A number of functions are written to accomplish these tasks. POP basically consists of writing of list of instructions(actions) for the machine to follow, & organizing these instructions into groups known as functions.

4 Typical structure of POP

5 In POP, concentration was given more on the development of functions, and very little attention is given to the data that are being used by various functions. Usage of global data in a multi function program. In a large program it is very difficult to identify what data is used by which function. The serious drawback with POP is that it doesn’t model real world problems very well. Because functions are action – oriented.

6 Characteristics of POP
Emphasis is on doing things(functions). Large programs are divided into smaller programs known as functions Most of the functions share global data. Data move openly from one function to another Functions transform data from one from to another. Follows top-down approach. COBOL, FORTRAN and C are POPs.

7 Object Oriented Programming (OOP)
OOP treat data as a critical element in the program development & doesn’t allow it to flow freely around the system. It ties data more closely to the function that operates on it and protects it from accidental modification from outside functions OOP allows decomposition of a problem into a number of entities called objects and then builds data functions and objects around these objects.

8 Organization of data & functions in OOP

9 Characteristics of OOP
Emphasis is on data rather than procedure. Programs are divided into objects. Functions that operate on the object’s data are tied together. Data is hidden & can’t be accessed by external functions. Objects may communicate with each other through functions. New data & functions can be easily added whenever necessary. Follows bottom-up approach.

10 Basic Concepts of OOP Objects Classes Data abstraction & encapsulation
Inheritance Polymorphism Dynamic binding Message Passing.

11 Object Objects are real world entities.
They may represent a person, a place, a bank account, a table of data or any item that the program has to handle. Objects takes up space in the memory and have an associated address. When a program is executed, the objects interact by sending messages to one another.

12 Representation of an object

13 Classes Objects contain data and code to manipulate that data.
The entire set of data and code can be grouped and put inside a class. Objects are variables of type class. Once a class has been defined we can create any number of objects belonging to that class. A class is collection of objects of similar type. For ex, mango, apple and orange are members of the class fruit.

14 Class Representation

15 Data Abstraction & Encapsulation
The wrapping up of data and function into a single unit (class) is known as encapsulation. Data is not accessible to the outside world, and only those functions which are wrapped in the class can access it. These functions provide interface between the object’s data and the program. This insulation between the object’s data from direct access by program is called data hiding or information hiding.

16 Abstraction refers to the act of representing essential features without including the background details or explanation. C++ classes provides great level of data abstraction. They provide sufficient public methods to the outside world to play with the functionality of the object and to manipulate object data, i.e., state without actually knowing how class has been implemented internally. For example, your program can make a call to the sort() function without knowing what algorithm the function actually uses to sort the given values.

17 Inheritance Inheritance is the process by which objects of one class acquire the properties of objects of another class. It supports hierarchical classification The derived class shares common characteristics with the class from which it is derived. Inheritance provides the idea of resuability.

18 Inheritance

19 Polymorphism Ability to take more than one form.
An operation may exhibit different behavior in different instances. The behavior depends on the types of data used in the operation. For ex, addition operation generates sum if two operands are integers and concatenates the strings, if two operands are strings. Making an operator to exhibit different behaviors in different instances is known as operator overloading.

20 A single function can be used to handle different number and different types of arguments.
Using single function name to perform different types of tasks is known as function overloading. Polymorphism allows objects having different structure to share the same external interface.

21 Class shape

22 Dynamic Binding Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (late binding) means codes associated with the given procedure call is not known until the time of the call at run-time. In the previous example, draw procedure is redefined in each class that defines object and at runtime, the code matching the object under current reference will be called.

23 Message Passing An OOP consists of set of objects that communicate with each other. The programming process involves following steps: creating class that defines objects and their behavior Creating objects from class definition. Establishing communication among objects

24 Objects communicate with one another by sending & receiving information .
A message for an object is a request for execution of a procedure and therefore will invoke function in the receiving object that generates the desired result. Message passing involves specifying the name of the object, the name of the function(message) and the information to be sent.

25 Objects have life cycle. They can be created and destroyed.
Communication with an object is feasible as long as it is alive.

26 First C++ Program #include<iostream.h> using namespace std; int main() { cout<< “ C++ is better than C .\n”; //C++ statem ent return 0; }

27 <iostream> header :
Header that defines the standard input/output stream objects Contains the declaration for identifier cout and operator <<. It should be included in the beginning of the program .h is not necessary

28

29

30

31

32

33 Structure of a C++ Program

34 Classes Classes are created using the keyword class.
A class declaration defines a new type that links code and data. This new type is then used to declare objects of that class. In other words, an object is an instance of a class. A class declaration is similar syntactically to a structure.

35 class declaration that does not inherit any other class.
class class-name { private data and functions access-specifier: data and functions // ... } object-list; The object-list is optional. If present, it declares objects of the class. Here, access-specifier is one of these three C++ keywords: public private protected

36 By default, functions and data declared within a class are private to that class and may be accessed only by other members of the class. The public access specifier allows functions or data to be accessible to other parts of your program. The protected access specifier is needed only when inheritance is involved. Once an access specifier has been used, it remains in effect until either another access specifier is encountered or the end of the class declaration is reached.

37 Class members that have been declared as private can be accessed only from within the class.
Public members can be accessed from outside the class. The data hiding is achieved using private declaration. Variables declared inside are called as data members of a class. Functions declared inside a class are known as member functions

38

39 A simple class example

40 Creating objects A class provides the blueprints for objects, so basically an object is created from a class. We declare objects of a class with exactly the same sort of declaration that we declare variables of basic types.  Item x; //memory for x is created In c++, class variables are known as objects, therefore x is an object of class item. We can declare multiple objects in one statement. Item x,y,z;

41 Objects can also be created when a class is defined by placing their names immediately after the closing brace.

42 Accessing class members
The private data of a class can be accessed only through the member functions. So the main() function cannot contain a statements that access number and cost directly. The following is the format for calling a function:

43 For example, x.getdata(100, 75.5); //implements getdata() function x.putdata(); //displays values x.number=10; //illegal X can be accessed only through the member functions

44

45 Defining member functions
Member functions can be defined in 2 ways: Outside the class definition Inside the class definition. An important difference between a member function and a normal function is that a member function uses identity label in the header. This label tells compiler which class the function belongs to.

46 The general form of member function is:
The membership label class-name:: tells compiler that function function-name belongs to the class class-name. The scope of the function is restricted to the class-name specified in the header. The symbol :: is called scope resolution operator

47 The getdata() and putdata() function may be defined as follows:

48 Characteristics of member functions
several different classes can use the same function name. the membership label will resolve their scope. Member functions can access the private data. A non-member function can not do so. A member function can call another member function directly without using dot operator.

49 Inside the class definition

50 A simple c++ program

51

52 Output

53 Making outside function inline
We can define a member function outside the class definition and can make it inline by just using the inline keyword in the header line of function definition.

54 Nesting of Member Functions
class nest_fun { int l,b,area; public: void input(); void output(int,int); }; void nest_fun::input() cout<<”Enter length and breadth of rectangle: “; cin>>l>>b; output(l,b); } void nest_fun::output(int l,int b) cout<<”Length = “<<l<<” Breadth= “<<b<<endl; area=l*b; cout<<”Area of rectangle: “<<area;

55 void main() { nest_fun n1; clrscr(); n1.input(); getch(); }

56 Data hiding Data hiding is key feature of OOP.
It is achieved by declaring variables and member functions “private”. By default, the members of a class are private. A private member function can be only called by another function that is a member of its class. Even an object of a class cannot invoke private function using dot operator.

57 Private member functions
We can also place member functions under private section. A private member function can only be called by another member function that is member function of its class. Even an object cannot invoke a private function using dot operator.

58 If s1 is an object of sample then,
s1.read(); //illegal However read() can be called by function update to update the value of m. Void sample::update() { read(); }

59 Memory allocation for objects
The member functions are created and placed in the memory space only once when they are defined as a part of the class specification. Since all the objects belonging to that class use the same member functions, no separate space is allocated for member functions when the objects are created. Only space for data members is allocated separately for each object. Because different data members may hold different data values for different objects.

60

61 Arrays within a CLASS The arrays can be used as member variables in a class. const int size = 10; class matrix { int mat [ size ] ; public: void getval ( ) ; void putval ( ) ; };

62 Constructors It is very common for some part of an object to require initialization before it can be used. Because the requirement for initialization is so common, C++ allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor function. A constructor is a special function that is a member of a class and has the same name as that class.

63 Characteristics of constructors
A constructor has the same name as that of the class. A constructor is defined in the public section of the class definition. A constructor is invoked automatically as soon as the object is created. A constructor does not return any value, so return type is not associated with its definition. The constructors are not inherited. The const class objects cannot be initialized with a constructor. Constructors can be overloaded.

64 Class box { int length; int width; int height; public : Box(void)
} };

65 When we create box b;, The constructor box() is invoked automatically when b is created and initializes all three data members. The parameter list of the box constructor doesn’t accept any argument values here. The constructor that doesn’t accept any argument values is called a default constructor. If the constructor is not defined then the compiler will provide default constructor. Xyz x, invokes default constructor of the compiler to construct object x.

66 Parameterized Constructors
It may be necessary to initialize the various data elements of different objects with different values when they are created. This is achieved by passing arguments to the constructor function when the objects are created. The constructors that can take arguments are called parameterized constructors.

67 Parameterized Constructors
continue … When a constructor is parameterized, we must pass the initial values as arguments to the constructor function when an object is declared. Two ways Calling: Explicit add sum = add(2,3); Implicit add sum(2,3) Shorthand method class add { int m, n ; public : add (int, int) ; }; add : : add (int x, int y) m = x; n = y; }

68 Overloaded Constructors
C + + permits to use more than one constructors in a single class. Add( ) ; // No arguments Add (int, int) ; // Two arguments

69 Overloaded Constructors
continue … class add { int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;} }; The first constructor receives no arguments. The second constructor receives two integer arguments. The third constructor receives one add object as an argument.

70 Overloaded Constructors
continue … class add { int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;} }; Add a1; Would automatically invoke the first constructor and set both m and n of a1 to zero. Add a2(10,20); Would call the second constructor which will initialize the data members m and n of a2 to 10 and 20 respectively.

71 Overloaded Constructors
continue … class add { int m, n ; public : add ( ) {m = 0 ; n = 0 ;} add (int a, int b) {m = a ; n = b ;} add (add & i) {m = i.m ; n = i.n ;} }; Add a3(a2); Would invoke the third constructor which copies the values of a2 into a3. This type of constructor is called the “copy constructor”. Construction Overloading More than one constructor function is defined in a class.

72 Overloaded Constructors
continue … class complex { float x, y ; public : complex ( ) { } complex (float a) { x = y = a ; } complex (float r, float i) { x = r ; y = i } }; complex ( ) { } This contains the empty body and does not do anything. This is used to create objects without any initial values.

73 Overloaded Constructors
continue … C + + compiler has an implicit constructor which creates objects, even though it was not defined in the class. This works well as long as we do not use any other constructor in the class. However, once we define a constructor, we must also define the “do-nothing” implicit constructor.

74 Constructors with Default Arguments
It is possible to define constructors with default arguments. Consider complex (float real, float imag = 0); The default value of the argument imag is zero. complex C1 (5.0) assigns the value 5.0 to the real variable and 0.0 to imag. complex C2(2.0,3.0) assigns the value 2.0 to real and 3.0 to imag.

75 Constructors with Default Arguments
continue … A : : A ( )  Default constructor A : : A (int = 0)  Default argument constructor The default argument constructor can be called with either one argument or no arguments. When called with no arguments, it becomes a default constructor.

76 Dynamic Initialization of Objects
Providing initial value to objects at run time. Advantage – We can provide various initialization formats, using overloaded constructors. This provides the flexibility of using different format of data at run time depending upon the situation.

77 Copy Constructor A copy constructor is used to declare and initialize an object from another object. integer (integer & i) ; integer I 2 ( I 1 ) ; or integer I 2 = I 1 ; The process of initializing through a copy constructor is known as copy initialization.

78 Copy Constructor continue … The statement I 2 = I 1; Will invoke the copy constructor. If I 1 and I 2 are objects, this statement is legal and assigns the values of I 1 to I 2, member-by-member.

79 Copy Constructor continue … A reference variable has been used as an argument to the copy constructor. We cannot pass the argument by value to a copy constructor.

80 Destructors A destructor is used to destroy the objects that have been created by a constructor. Like constructor, the destructor is a member function whose name is the same as the class name but is preceded by a tilde. eg: ~ integer ( ) { }

81 Destructors continue … A destructor never takes any argument nor does it return any value. A destructor must be declared in public section. It will be invoked implicitly by the compiler upon exit from the program – or block or function as the case may be – to clean up storage that is no longer accessible. Destructors can not be overloaded.

82 When Constructors and Destructors Are Executed
As a general rule, an object's constructor is called when the object comes into existence, and an object's destructor is called when the object is destroyed. A local object's constructor is executed when the object's declaration statement is encountered. The destructors for local objects are executed in the reverse order of the constructor functions. Global objects have their constructors execute before main( ) begins execution. Global constructors are executed in order of their declaration, within the same file. Global destructors execute in reverse order after main( ) has terminated.

83 #include <iostream> using namespace std; class myclass { public: int who; myclass(int id); ~myclass(); } glob_ob1(1), glob_ob2(2); myclass::myclass(int id) { cout << "Initializing " << id << "\n"; who = id; }

84 myclass::~myclass() { cout << "Destructing " << who << "\n"; } int main() myclass local_ob1(3); cout << "This will not be first line displayed.\n"; myclass local_ob2(4); return 0;

85 Output Initializing 1 Initializing 2 Initializing 3 This will not be first line displayed. Initializing 4 Destructing 4 Destructing 3 Destructing 2 Destructing 1

86 Static Data Members A data member of a class can be qualified as static. Characteristics of static member variables: It is initialized to zero when the first object of its class is created. No other initialization is permitted. Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created. It is visible only within the class, but its lifetime is the entire program. Static variables are normally used to maintain values common to the entire class.

87 When we declare a static data member within a class, we are not defining it. (That is, we are not allocating storage for it.) Instead, we must provide a global definition for it elsewhere, outside the class. This is done by redeclaring the static variable using the scope resolution operator to identify the class to which it belongs. This causes storage for the variable to be allocated.

88

89 Int main() {

90 Output

91 Static Member Functions
Like static member variable, we can also have static member functions. Properties of member functions: A static function can have access to only other static members ( functions or variables ). A static member function can be called using the class name ( instead of its objects ) as: class-name : : function-name;

92

93

94 Output

95


Download ppt "Subject Name: Object Oriented Programming with C++"

Similar presentations


Ads by Google