Subject Name: Object Oriented Programming with C++

Slides:



Advertisements
Similar presentations
Classes & Objects INTRODUCTION : This chapter introduces classes ; explains data hiding, abstraction & encapsulation and shows how a class implements these.
Advertisements

Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
C++ fundamentals.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Learners Support Publications Pointers, Virtual Functions and Polymorphism.
CONCEPTS OF OBJECT ORIENTED PROGRAMMING. Topics To Be Discussed………………………. Objects Classes Data Abstraction and Encapsulation Inheritance Polymorphism.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Learners Support Publications Classes and Objects.
Programming Languages by Ravi Sethi Chapter 6: Groupings of Data and Operations.
Chapter 10 Introduction to Classes
Classes In C++ 1. What is a class Can make a new type in C++ by declaring a class. A class is an expanded concept of a data structure: instead of holding.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
Learners Support Publications Object Oriented Programming.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
9-Dec Dec-15  INTRODUCTION.  FEATURES OF OOP.  ORGANIZATION OF DATA & FUNCTION IN OOP.  OOP’S DESIGN.
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Chapter -6 Polymorphism
Introduction to Object-Oriented Programming Lesson 2.
Programming Fundamentals. Topics to be covered Today Recursion Inline Functions Scope and Storage Class A simple class Constructor Destructor.
Structure A Data structure is a collection of variable which can be same or different types. You can refer to a structure as a single variable, and to.
1 n Object Oriented Programming. 2 Introduction n procedure-oriented programming consists of writing a list of instructions and organizing these instructions.
Learners Support Publications Constructors and Destructors.
Welcome to Constructors and Destructors Prepared By Prepared By : VINAY ALEXANDER ( विनय अलेक्जेण्डर )PGT(CS) KV JHAGRAKHAND.
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Constructors and Destructors
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Lecture 3 (UNIT -1) SUNIL KUMAR CIT-UPES.
Classes C++ representation of an object
2 Chapter Classes & Objects.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
Abstract Data Types and Encapsulation Concepts
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
CONSTRUCTORS & DESTRUCTORS
Java Primer 1: Types, Classes and Operators
Review: Two Programming Paradigms
Chapter 3: Using Methods, Classes, and Objects
About the Presentations
Chapter 5 Classes.
Constructor & Destructor
Lecture 1 Introduction.
This pointer, Dynamic memory allocation, Constructors and Destructor
Lecture 4-7 Classes and Objects
Lecture 9 Concepts of Programming Languages
Abstract Data Types and Encapsulation Concepts
Introduction to Classes
Chapter 3 Introduction to Classes, Objects Methods and Strings
Chapter 9 Classes: A Deeper Look, Part 1
Procedural Programming
Dr. Bhargavi Dept of CS CHRIST
Polymorphism Polymorphism
Constructors and destructors
Constructors and Destructors
Classes and Objects.
Principles of object – oriented programming UNIT-1 Chapter-1.
UNIT I OBJECT ORIENTED PROGRAMMING FUNDAMENTALS
Introduction to Object-Oriented Programming
Submitted By : Veenu Saini Lecturer (IT)
Classes C++ representation of an object
Chapter 9 Introduction To Classes
Constructors & Destructors
More C++ Classes Systems Programming.
C++ Object Oriented 1.
Lecture 9 Concepts of Programming Languages
Presentation transcript:

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

Classes & Objects

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.

Typical structure of POP

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.

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.

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.

Organization of data & functions in OOP

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.

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

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.

Representation of an object

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.

Class Representation

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.

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.

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.

Inheritance

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.

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.

Class shape

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.

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

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.

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

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

<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

Structure of a C++ Program

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.

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

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.

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

A simple class example

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;

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

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:

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

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.

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

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

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.

Inside the class definition

A simple c++ program

Output

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.

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;

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

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.

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.

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

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.

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

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.

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.

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

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.

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.

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

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

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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.

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 ( ) { }

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.

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.

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

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;

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

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.

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.

Int main() {

Output

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;

Output