Oops concepts Object-orientation Objects and classes Overloading Inheritance Polymorphism Generic Programming Exception Handling Introduction to design.

Slides:



Advertisements
Similar presentations
Copyright © 2002 Pearson Education, Inc. Slide 1.
Advertisements

Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Learning Objectives Structures Structure types Structures.
1 Classes and Data Abstraction Chapter What a Class ! ! Specification and implementation Private and public elements Declaring classes data and.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Class and Objects.
EEM 480 Algorithms and Complexity by Assist. Prof. Dr. Emin Germen.
Chapter 3 Data Abstraction: The Walls. © 2005 Pearson Addison-Wesley. All rights reserved3-2 Abstract Data Types Modularity –Keeps the complexity of a.
 2006 Pearson Education, Inc. All rights reserved Midterm review Introduction to Classes and Objects.
Object Oriented Programming.  OOP Basic Principles  C++ Classes  September 2004  John Edgar 22.
C++ Classes in Depth. Topics Designing Your Own Classes Attributes and Behaviors Writing Classes in C++ Creating and Using Objects.
Chapter Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Lecture 9 Concepts of Programming Languages
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
1 C++ Structures Starting to think about objects...
Review of C++ Programming Part II Sheng-Fang Huang.
 2003 Prentice Hall, Inc. All rights reserved. 1 Introduction to Classes and Objects Outline Introduction Classes, Objects, Member Functions and Data.
Classes Mark Hennessy Dept. Computer Science NUI Maynooth C++ Workshop 18 th – 22 nd Spetember 2006.
 2006 Pearson Education, Inc. All rights reserved Classes: A Deeper Look.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
C++ How to Program, 8/e © by Pearson Education, Inc. All Rights Reserved. Note: C How to Program, Chapter 22 is a copy of C++ How to Program Chapter.
Chapter 6 Structures and Classes. Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-2 Structures  2 nd aggregate data type: struct  Recall:
CS212: Object Oriented Analysis and Design Lecture 6: Friends, Constructor and destructors.
Copyright © 2012 Pearson Education, Inc. Chapter 13: Introduction to Classes.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13: Introduction to Classes.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
Chapter 13. Procedural programming vs OOP  Procedural programming focuses on accomplishing tasks (“verbs” are important).  Object-oriented programming.
Learners Support Publications Classes and Objects.
C++ Review (3) Structs, Classes, Data Abstraction.
Copyright 2004 Scott/Jones Publishing Alternate Version of STARTING OUT WITH C++ 4 th Edition Chapter 7 Structured Data and Classes.
Chapter 10 Introduction to Classes
CS1201: Programming Language 2 Classes and objects By: Nouf Aljaffan Edited by : Nouf Almunyif.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Simple Classes. ADTs A specification for a real world data item –defines types and valid ranges –defines valid operations on the data. Specification is.
Introduction to c++ programming - object oriented programming concepts - Structured Vs OOP. Classes and objects - class definition - Objects - class scope.
CLASSES : A DEEPER LOOK Chapter 9 Part I 1. 2 OBJECTIVES In this chapter you will learn: How to use a preprocessor wrapper to prevent multiple definition.
Programming Fundamentals1 Chapter 8 OBJECT MANIPULATION - INHERITANCE.
Structures and Classes Version 1.0. Topics Structures Classes Writing Structures & Classes Member Functions Class Diagrams.
OOP using C Abstract data types How to accomplish the task??? Requirements Details Input, output, process Specify each task in terms of input.
2 Objectives You should be able to describe: Object-Based Programming Classes Constructors Examples Common Programming Errors.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
EGR 2261 Unit 11 Classes and Data Abstraction  Read Malik, Chapter 10.  Homework #11 and Lab #11 due next week.  Quiz next week.
CSci 162 Lecture 10 Martin van Bommel. Procedures vs Objects Procedural Programming –Centered on the procedures or actions that take place in a program.
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.
1 Classes II Chapter 7 2 Introduction Continued study of –classes –data abstraction Prepare for operator overloading in next chapter Work with strings.
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Slide 1 Chapter 6 Structures and Classes. Slide 2 Learning Objectives  Structures  Structure types  Structures as function arguments  Initializing.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
نظام المحاضرات الالكترونينظام المحاضرات الالكتروني Object Oriented Programming(Objects& Class) Classes are an expanded concept of data structures: like.
Introduction to Classes in C++ Instructor - Andrew S. O’Fallon CptS 122 Washington State University.
1 Introduction to Object Oriented Programming Chapter 10.
Lecture #6 Classes and Objects.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 13: Introduction to Classes.
Programming Fundamentals1 Chapter 7 INTRODUCTION TO CLASSES.
Copyright © 2006 Pearson Addison-Wesley. All rights reserved. 6-1 Learning Objectives  Classes  Constructors  Principles of OOP  Class type member.
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.
Mr H Kandjimi 2016/01/03Mr Kandjimi1 Week 3 –Modularity in C++
Data Structures Lecture 4: Classes in C++ Azhar Maqsood NUST Institute of Information Technology (NIIT)
Computer Programming II Lecture 5. Introduction to Object Oriented Programming (OOP) - There are two common programming methods : procedural programming.
Procedural and Object-Oriented Programming
Review: Two Programming Paradigms
Chapter 5 Classes.
Lecture 9 Concepts of Programming Languages
Introduction to Classes
Classes and Objects.
Introduction to Classes and Objects
Lecture 8 Object Oriented Programming (OOP)
Lecture 9 Concepts of Programming Languages
Introduction to Classes and Objects
Presentation transcript:

Oops concepts Object-orientation Objects and classes Overloading Inheritance Polymorphism Generic Programming Exception Handling Introduction to design patterns

Learning Objectives Structure Definition Classes vs. Objects Interface and Implementation Constructors and Destructors Set and get Functions Constant Objects and constant Member

structure Structure is a convenient tool for handling a group of logically related data items array: collection of values of same type Structure: collection of values of different types It is a user-defined data type with a template that serves to define its data properties. Example: Struct student { char name[20]; int roll_number; float total_marks; }; The keyword Struct declares student as a new data type that can hold three fields of different data types. These fields are known as structure members or elements.

Conti… Definition: struct Student  Name of new struct "type" { char name[10];  member names int id; int secno; };

Limitations of structure We cannot process two complex numbers to any other specification Example: C3= C1 + C2 Structures do not permit data hiding. Example: C=1.233 Dot Operator (.) to access members –s1.name –s1.id –s1.secno

Class vs Object “Class “ refers to a blueprint. It defines the variables and methods the objects support. It is the basic unit of encapsulation. It also defines as the collection of a similar types of objects. “Object” is an instance(properties) of a class. Each object has a class which defines its data and behaviour.

Cont.. Software objects model real-world objects or abstract concepts E.g. dog, bicycle, queue Real-world objects have states and behaviors Dogs' states: name, color, breed, hungry Dogs' behaviour: barking, fetching, sleeping

Example A class is like a blueprint. Out of a blueprint, a builder can build a house. One class can be reused many times to make many objects of the same class Struct Time { int hour; int minute; int second; }; Class Time can be used to create many Time objects Like wakeup time, breakfast time, lunch time, dinner time, bed time, ….

Cont… Class is a tool to realize objects Class is a tool for defining a new type Example: Lion is an object Student is an object Both has some attributes and some behaviors

Classes Similar to structures –Adds member FUNCTIONS –Not just member data Integral to object-oriented programming –Focus on objects Object: Contains data and operations In C++, variables of class type are objects Class Definitions: Defined similar to structures Example: class Rectangle  name of new class type { public: int width;  member data int height; void set_values();  member function! }; Notice only member function’s prototype –Function’s implementation is elsewhere

Class

Example

Why Member Function The Function components of a class are called a member function They model the behaviour of an object Objects can make their data invisible Object remains in consistent state Classes that can be used to instantiate objects are called concrete classes.

Example Class person //New data type { Char name[30]; Int age; Public: void getdata(void); void display (void); }

Example Void person :: getdata(void) //member function { cout<< “ Enter name: “ ; cin >> name; cout << “Enter age: “ ; cin >> age; } Void person :: displayl (void) //member function { cout << “\n Name: “ << name; cout << “\n Age: “ << age ; } Main() { person p; //object of type person p.getdata() ; p.display(); } Output Enter name: xxxx Enter age : 18 Name:xxxx Age:18

Class Member Access Members accessed same as structures Example: rect.width; rect.height; –And to access member function: rect.set_values();  Invokes member function Class Member Functions Must define or "implement" class member functions Like other function definitions –Can be after main() definition –Must specify class: void Rectangle::set_values() {…} :: is scope resolution operator Instructs compiler "what class" member is from Item before :: called type qualifier

Class Member Functions Definition Notice output() member function’s definition (in next example) Refers to member data of class –No qualifiers Function used for all objects of the class –Will refer to "that object’s" data when invoked –Example: today.output(); Displays "today" object’s data 6-17

#include using namespace std; class Rectangle { int width, height; public: void set_values (int,int); int area() {return width*height;} }; void Rectangle::set_values (int x, int y) { width = x; height = y; } int main () { Rectangle rect; rect.set_values (3,4); cout << "area: " << rect.area(); return 0; } 6-18

Interface and Implementation An interface describes the behavior or capabilities of a C++ class without committing to a particular implementation of that class. The C++ interfaces are implemented using abstract classes and these abstract classes should not be confused with data abstraction which is a concept of keeping implementation details separate from associated data. A class is made abstract by declaring at least one of its functions as pure virtual function. A pure virtual function is specified by placing "= 0" in its declaration as follows: class Box { public: // pure virtual function virtual double getVolume() = 0; private: double length; // Length of a box double breadth; // Breadth of a box double height; // Height of a box }; A request for an object to perform one of its operations (methods) All communication between objects is done via messages Interfaces Messages define the interface to the object Everything an object can do is represented by its message interface The interfaces provide abstractions You shouldn't have to know anything about what is in the implementation in order to use it (black box) An interface is a set of operations (methods) that given object can perform

Interface and Implementation public: The member (data or function) is accessible and available to all in the system. private: The member (data or function) is accessible and available within this class only. Instead of putting all the codes in a single file. We shall "separate the interface and implementation" by placing the codes in 3 files. Circle.h: defines the public interface of the Circle class. Circle.cpp: provides the implementation of the Circle class. TestCircle.cpp: A test driver program for the Circle class.

Public and Private Members Data in class almost always designated private in definition! –Upholds principles of OOP –Hide data from user –Allow manipulation only via operations Which are member functions Public items (usually member functions) are "user-accessible“ Example : Modify previous example: class Rectangle { public: void setvalues(); private: int width, height; }; Data now private,Objects have no direct access Declare object: Rectangle rect; Object rect can ONLY access public members –cin >> rect.width; cout << rect.height; // NOT ALLOWED! –Must instead call public operations: rect.setvalues();

Cont… #include using namespace std; // Base class class Shape { public: // pure virtual function providing interface framework. virtual int getArea() = 0; void setWidth(int w) { width = w; } void setHeight(int h) { height = h; } protected: I nt width; I nt height; };

Cont… // Derived classes class Rectangle: public Shape { public: int getArea() { return (width * height); } };

Con… class Triangle: public Shape { public: int getArea() { return (width * height)/2; } }; int main(void) { Rectangle Rect; Triangle Tri; Rect.setWidth(5); Rect.setHeight(7); // Print the area of the object. cout << "Total Rectangle area: " << Rect.getArea() << endl; Tri.setWidth(5); Tri.setHeight(7); // Print the area of the object. cout << "Total Triangle area: " << Tri.getArea() << endl; return 0; } When the above code is compiled and executed, it produces the following result: Total Rectangle area: 35 Total Triangle area: 17

Cont… Circle.h-Header /* The Circle class Header (Circle.h) */ #include // using string using namespace std; // Circle class declaration class Circle { private: // Accessible by members of this class only // private data members (variables) double radius; string color;

cont.. public: // Accessible by ALL // Declare prototype of member functions // Constructor with default values Circle(double radius = 1.0, string color = "red"); // Public getters & setters for private data members double getRadius() const; void setRadius(double radius); string getColor() const; void setColor(string color); // Public member Function double getArea() const; };

Constructors and Destructors

Cont..

Destructors As the name Implies, is used to destroy the objects that have been created by a constructor. The destructor is a member function whose name is the same as the class name but is preceded by a tilde(~). Whenever new is used to allocate memory in the constructors, we should use delete to free that memory.

Example Matrix:: ~matrix () { for (int = 0; i< d1; i++) delete p[i]; delete p; }

Cont… Example: ~ stack() { delete []a; cout<<"\n Destructing the stack"; }

Functions Functions allow to structure programs in segments of code to perform individual tasks. In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is: type name ( parameter1, parameter2,...) { statements } Where: -type is the type of the value returned by the function. -name is the identifier by which the function can be called. -parameters (as many as needed): Each parameter consists of a type followed by an identifier, with each parameter being separated from the next by a comma. Each parameter looks very much like a regular variable declaration (for example: int x), and in fact acts within the function as a regular variable which is local to the function. The purpose of parameters is to allow passing arguments to the function from the location where it is called from. -statements is the function's body. It is a block of statements surrounded by braces { } that specify what the function actually does.

Cont… // function example #include using namespace std; int addition (int a, int b) { int r; r=a+b; return r; } int main () { int z; z = addition (5,3); cout << "The result is " << z; }

Set and get functions Classes often provide public member functions to allow clients of the class to set ( write) or get (read) the values of private datamembers. Specifically a member function that sets data member InteresRate might be named setInterestRate and a member function that gets the InterestRate might be named getInterestRate. Get functions are also commonly called “query” functions.

Example // set functions setTime (int, int, int); // set hour,minute,second setHour (int); //set hour setMinute(int);//set minute set second (int);//set second // get functions Int getHour () ; // return hour Int getMinute(); // return minute Int getSecond(); // return second

Constant Objects and Constant Member Protect argument –Use constant parameter Also called constant call-by-reference parameter –Place keyword const before type –Makes parameter "read-only" –Attempt to modify parameter results in compiler error Some objects need to be modifiable and some do not modify const Time noon (12, 0, 0); Declares a const object noon of class Time and initializes it to 12 noon. A const object cannot be modified by assignment so it must be initialized. When a data member of a class is declared const, a member initializer must be used to provide the constructor with the initial value of the data member for an object of the class.

Cont… If a member function does not alter any data in the class, then may declare it as a const member function void mul(int,int) const; double get balane() const; The qualifier const is appended to the fuction prototypes(in both declaration and definition). The compiler will generate an error message if such functions try to alter the data values.

Cont… Stacks are a type of container adaptor, specifically designed to operate in a LIFO context (last-in first- out), where elements are inserted and extracted only from one end of the container. Create a class to implement the data structure STACK. 1. Write a constructor to initilize the Top of the STACK to 0. write a Member function PUSH(), To insert and element and member function POP(). To delete an element check for overflow and under flow condition.

Write a program to implement the data structure STACK as class and write a constructor to initialize the TOP of the STACK to 0. Write a member function PUSH () to insert an element and member function POP () to delete an element and LIST () to display all elements in the STACK. Check for overflow and under flow condition. #include using namespace std; class STACK { int tos,* a, max; public: STACK( int s) { tos=0; max=s; a=new int[s]; } ~ STACK ( ) { delete [ ]a; cout << "\n Destructing the stack"; } void PUSH(int); void POP(); void VIEW(); }; Example

void STACK :: PUSH( int item) { if(tos ==max-1) cout<<"The stack is full \n "; else { tos ++; a[tos]=item; cout<<"\n"<<item<<" Inserted into stack"; } return ; } void STACK :: POP( ) { int i; if (tos==0) { cout<<"stack is empty"; return (0); } else { i=a[tos]; tos --; return(i); }

void STACK :: VIEW() { int i ; if (tos==0) cout<<"stack is empty\n"; else { cout<<" The elements of stack are"<<"\n"; for (i=tos; i>=1; i--) cout<<"\n"<<a[i]; } int main() { int s,n,c, item; cout<<"\n Enter the Size of stack:"; cin>>s; stack st(s); STACK st(s); do { cout<<"\n 1.Push\n 2.Pop\n 3.View\n 4.Exit"; cin>>c;

switch(c) { case 1: cout<<"\n Enter the element to be pushed:"; cin>>n; st.PUSH(n); break; case 2: item=st.POP(); if(item==0) cout<<"\n UNDERFLOW"; else cout<<"\n"<<item<<" has been removed from stack"; break; case 3: st.VIEW(); break; case 4: cout<<"\nExit"; break; default: cout<<"\n Enter the correct choice:"; break; } }while(c!=4); }