object oriented
play

Object Oriented Object 3 Programming Object 1 Object 2 Object 4 - PDF document

4/13/2017 OOP Object Oriented Object 3 Programming Object 1 Object 2 Object 4 For : COP 3330. Object oriented Programming (Using C++) ht t p: / / www. com pgeom . com / ~pi yush/ t each/ 3330 Objects: State (fields), Behavior (member


  1. 4/13/2017 OOP Object Oriented Object 3 Programming Object 1 Object 2 Object 4 For : COP 3330. Object oriented Programming (Using C++) ht t p: / / www. com pgeom . com / ~pi yush/ t each/ 3330 Objects: State (fields), Behavior (member functions), Identity Class : Blue print of an object. Data and behavior are strongly linked in OOP. Objects are responsible for their behavior. Example: Complex numbers, Rational numbers, Floating point numbers Piyush Kumar , all understand addition. OOP components Recap: ADTs  Data Abstraction  Specify the meaning of the  Information Hiding, ADTs operations independent of any  Encapsulation implementation/definition.  Type Extensibility  Least common denominator of all  Operator Overloading possible implementations.  Inheritance  Information Hiding: Do not  Code Reuse expose unnecessary information.  Polymorphism Inheritance Inheritance  Two example classes  Two example classes  Class Employee  Class Manager class Employee { class Manager { public: public: Employee(string theName, float PayRate); Manager(string theName, float PayRate); string Name() const; void set_manages(int n); float PayRate() const; string Name() const; float compute_pay(float hoursWorked) const; float PayRate() const; protected: float compute_pay(float hoursWorked) const; string name; protected: float payrate; string name; }; float payrate; int manages_n_employees; }; 1

  2. 4/13/2017 Reuse Manager  We have done unnecessary work to create class Manager : public Employee { // is a relationship Manager, which is similar to (and really is a public: “ is a ") Employee. Manager(string theName, float PayRate, int n);  We can fix this using the OO concept of void set_manages(int n); protected: inheritance . int manages_n_employees;  We let a manager inherit from an employee. };  A manager gets all the data and functionality of an employee after inheritance. Methods of Manager have access to name, payrate because they were  We can then add any new data and methods declared in Employee as "protected” . needed for a manager and redefine any methods that differ for a manager. More on Inheritance : Inheritance Access privileges.  In a public inheritance:  Derive a new class (subclass) from an existing class (base class).  Public members are accessible to derived class.  Syntax: • class classname : access-label base-class { … }  Protected members are accessible to • Access-labels = { public, private, protected } derived class. These members are not accessible to the users of the base  Inheritance creates a hierarchy of class. related classes (types) which share  Private members are not accessible to code and interface. derived class. More Examples More Examples Person Base Class Derived Classes Student GradStudent Student UnderGradStudent Employee Shape Circle Triangle Rectangle UnderGradStudent GradStudent Non-Faculty Faculty Tetrahedron Loan CarLoan HomeImprovementLoan MortgageLoan Tenure Teaching “Is a” relationships. 2

  3. 4/13/2017 Inheritance: Subclass Inheritance  Derived classes contain their base  Code reuse classes as subobjects. • derive GradStudent from Student (also adds fields/methods) Manager object.  Specialization: Customization Employee object • derive bounded-stack from stack string name; float payrate; (by overriding/redefining push ) int manages_n_employees;  Generalization: Factoring Commonality  Functions in the derived may use  Avoid code-duplications (why?) members from the base. There is no requirement that the compiler lay out the base and derived parts of an object contiguously. Inheritance Open-Closed principle in OOP  A class must be defined to be used as a  The open/closed principle states base class. that a class must be both open and  A derived class can be used as a base- closed. class.  Open: means it has the ability to be  Forward declarations are same for base- extended classes as well as derived classes.  Closed: means it cannot be modified  class Manager; other than by extension.  class Employee;  class Manager: public employee; // Error An interesting paper: http://www.craiglarman.com/articles/The%20Importance%20of%20Being%20Closed%20-%20Larman%20-%20IEEE%20Software.pdf Open-Closed principle in OOP Example : Open-Closed Pr. Queue TestQueue  Once a class has been approved for use after having gone through code reviews, unit tests, and other Client ( Composition ) qualifying procedures, you don't want Subclass ( Inheritance ) to change the class very much, just extend it.  Changing base class can complicate DeltaBoundedQueue TestBoundedQueue all derived classes. 3

  4. 4/13/2017 More on Inheritance Virtual Methods  A pointer to a derived class can  A base class must indicate which of its always be used as a pointer to a base member functions it intends its class when public inheritance is used. derived classes to redefine. (But not vice-versa)  These member functions are defined  Private base classes are different as “virtual” in the base class.  STL Containers which need to contain both base/derived classes should be made of pointers to base classes.  Otherwise : Slicing problem. Example Dynamic Binding class Base { public: int i;  Allows invocation of general methods virtual void print() Base *bp; using a base class pointer. { Derived d; cout << "i value is " << i bp = &d;  The fact that a reference or pointer << " inside object of type Base\n\n"; bp->print(); // invokes } might refer to either a base or derived- }; class object is the key to dynamic class Derived: public Base { binding. public: virtual void print()  Allows easy extensibility. { cout << "i value is " << i << " inside object of type Derived\n\n"; } }; Dynamic Vs Static Binding Dynamic Vs Static Binding  Static Binding: The compiler uses the  Static Binding type of the pointer to find out which  Less time and space overhead. method to call.  Inlining possible  Dynamic Binding: The decision is  Dynamic Binding made at runtime. (uses ‘virtual’  Extensibility keyword)  Better code-reuse. 4

  5. 4/13/2017 Dynamic Vs Static Binding Virtual Functions  Have a fixed interface.  Efficiency Vs Flexibility  Derived implementations can change.  Static Binding  Dispatched using object’s “dynamic  More efficient type” to select the appropriate • Less time and space overhead, can use inlining. method.  Dynamic Binding  “Once Virtual, always virtual” rule.  Flexible: Enables extension of behavior of a system easily.  Once a base-class defines a function as virtual, it remains virtual through out the inheritance hierarchy. An example base class Scoping rules // Item sold at an undiscounted price // derived classes will define various discount strategies  In a public base class, public and class Item_base { friend std::istream& operator>>(std::istream&, Item_base&); protected members of the base class friend std::ostream& operator<<(std::ostream&, const Item_base&); public: virtual Item_base* clone() const { return new Item_base(*this); } remain public and protected members public: Item_base(const std::string &book = "", double sales_price = 0.0): isbn(book), price(sales_price) { } of the derived class. std::string book() const { return isbn; }  Example: // returns total sales price for a specified number of items // derived classes will override and apply different discount algorithms class circle: public point {}; virtual double net_price(std::size_t n) const { return n * price; } circle c; // no work, but virtual destructor needed // if base pointer that points to a derived object is ever deleted //can call point::move(int,int) virtual ~Item_base() { } // Always virtual. Why? (Hint: Static Vs Dynamic Binding) private: std::string isbn; // identifier for the item c.move(1,2); protected: double price; // normal, undiscounted price }; Out of scope of this class. Do not use. Scoping Rules. “Is a” Vs “Has a”  Private derivation:  Inheritance  public base class members are private in derived  Considered an “Is a” class relationship class.  e.g.: An HourlyEmployee “is a” Employee  Example:  A Convertible “is a” Automobile class stack: private linkedList {};  A class contains objects of another class stack s; as it’s member data s.insert(1,2);  Considered a “Has a” class relationship // cannot call linkedList::insert(int,int) where insert is public  e.g.: One class “has a” object of another  Protected derivation: class as it’s data  public base class members are protected in derived class. 5

  6. 4/13/2017 OOP Shape Example Abstract Base class: Shape. class Shape { shape public: Shape ( Point2d& position, Color& c) : center_(position) , color_ (c) {}; virtual void rotate( double radians ) = 0; virtual bool draw(Screen &) = 0; virtual ~Shape(void) = 0; rectangle void move(Point2d& p) { _center = p; }; • • • • private: circle Point2d center_; triangle Color color_; }; Public inheritance: “Is A” relationships C++ Shape example class Triangle: public Shape { public: Triangle( Point2d& p[3] ); virtual void rotate ( double radians ){…} virtual bool draw(Screen &s) {…}; virtual ~Triangle(void) {…}; private: Point2d vertices[3]; Color color_; }; 6

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend