Inheritance in C++ Eric Roberts CS 106B March 1, 2013.

Slides:



Advertisements
Similar presentations
Basic Object-Oriented concepts. Concept: An object has behaviors In old style programming, you had: –data, which was completely passive –functions, which.
Advertisements

Chapter 1 Object-Oriented Concepts. A class consists of variables called fields together with functions called methods that act on those fields.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Week 8 Recap CSE 115 Spring Composite Revisited Once we create a composite object, it can itself refer to composites. Once we create a composite.
Object Oriented Programming Chapter 7 Programming Languages by Ravi Sethi.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology/George Koutsogiannakis 1.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 Chapter 12 More OOP, Interfaces, and Inner Classes.
Unit 021 Abstract Classes What is an Abstract Class? Properties of an Abstract Class Discovering Abstract Classes.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
CS102--Object Oriented Programming Lecture 7: – Inheritance Copyright © 2008 Xiaoyan Li.
1 Lecture 06(Abstract Classes)Lecture 9 Abstract Classes Overview  Abstract Classes: A Definition.  Declaring Abstract Classes.  Abstract Methods: A.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
June 1, 2000 Object Oriented Programming in Java (95-707) Java Language Basics 1 Lecture 3 Object Oriented Programming in Java Language Basics Classes,
1 Chapter 6 Inheritance, Interfaces, and Abstract Classes.
ObjectDraw and Objects Early Chris Nevison Barbara Wells.
Chapter 3 - Introduction to Java Applets Outline 3.1Introduction 3.2Thinking About Objects 3.4A Simple Java Applet: Drawing a String 3.5Two More Simple.
Chapter 10 Classes Continued
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
Chapter 11: Inheritance and Polymorphism Java Programming: Program Design Including Data Structures Program Design Including Data Structures.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Basic Object- Oriented Concepts Presented By: George Pefanis 21-Sep-15.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
6-1 © 2004, D.A. Watt, University of Glasgow 6 Data Abstraction  Packages and encapsulation.  Abstract types.  Classes, subclasses, and inheritance.
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Objective-C1 CS151 Presentation: Objective C Kai Tai Pang William Sze.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Programming in Java CSCI-2220 Object Oriented Programming.
Object Oriented Software Development
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
Abstract Classes and Interfaces 5-Dec-15. Abstract methods You can declare an object without defining it: Person p; Similarly, you can declare a method.
Rina System development with Java Instructors: Rina Zviel-Girshin Lecture 4.
Introduction to Java Chapter 7 - Classes & Object-oriented Programming1 Chapter 7 Classes and Object-Oriented Programming.
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Programming Abstractions Cynthia Lee CS106X. Inheritance Topics Inheritance  The basics › Example: Stanford GObject class  Polymorphism › Example: Expression.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Chapter 8 Class Inheritance and Interfaces F Superclasses and Subclasses  Keywords: super F Overriding methods  The Object Class  Modifiers: protected,
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Simple Java Eric Roberts CS 106A January 11, 2016.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
CS 116 Object Oriented Programming II Lecture 9 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
 The word static is used to declare either a ________ variable or method.  Why do we use statics?  What is Polymorphism? class In general, we use a.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Modern Programming Tools And Techniques-I
Object-Oriented Concepts
7.1 What Is An Object Object-oriented program - Description or simulation of application Object-oriented programming is done by adopting or extending an.
Inheritance and Polymorphism
COP 3331 Object Oriented Analysis and Design Chapter 5 – Classes and Inheritance Jean Muhammad.
12 Data abstraction Packages and encapsulation
CS 106A, Lecture 12 More Graphics
Java Programming Language
SSEA Computer Science: Track A
Java Inheritance.
Chapter 14 Abstract Classes and Interfaces
Presentation transcript:

Inheritance in C++ Eric Roberts CS 106B March 1, 2013

Class Hierarchies Much of the power of modern object-oriented languages comes from the fact that they support class hierarchies. Any class can be designated as a subclass of some other class, which is called its superclass. Each subclass represents a specialization of its superclass. If you create an object that is an instance of a class, that object is also an instance of all other classes in the hierarchy above it in the superclass chain. When you define a new class in C++, that class automatically inherits the behavior of its superclass. Although C++ supports multiple inheritance in which a class can inherit behavior from more than one superclass, the vast majority of class hierarchies use single inheritance in which each class has a unique superclass. This convention means that class hierarchies tend to form trees rather than graphs.

Simplified View of the Stream Hierarchy ios clear() fail() eof() ostream put() << istringstream istringstream( s ) ofstream open( cstr ) close() ostringstream str() istream get() unget() >> ifstream open( cstr ) close()

Representing Inheritance in C++ class subclass : public superclass { body of class definition }; The first step in creating a C++ subclass is to indicate the superclass on the header line, using the following syntax: You can use this feature to specify the types for a collection class, as in the following definition of StringMap : class StringMap : public Map { /* Empty */ }; This strategy is useful in Pathfinder, because it lets you define a PathfinderGraph class with specific node and arc types: class PathfinderGraph : public Graph { additional operations you want for your graph };

Differences between Java and C++ In Java, defining a subclass method automatically overrides the definition of that method in its superclass. In C++, you have to explicitly allow for overriding by marking the method prototype with the keyword virtual. In Java, all objects are allocated dynamically on the heap. In C++, objects live either on the heap or on the stack. Heap objects are created using the keyword new and are referred to by their address. Stack objects take a fixed amount of space determined by the number and size of the instance variables. In Java, it is always legal to assign an object of a subclass to a variable declared to be its superclass. While that operation is technically legal in C++, it rarely does what you want, because C++ throws away any fields in the assigned object that don’t fit into the superclass. This behavior is called slicing. By contrast, it is always legal to assign pointers to objects.

The Employee Hierarchy Employee getName() virtual getPay() SalariedEmployee setSalary( salary ) virtual getPay() CommissionedEmployee setBaseSalary( dollars ) setCommissionRate( rate ) setSalesVolume( dollars ) virtual getPay() HourlyEmployee setHourlyRate( wage ) setHoursWorked( hours ) virtual getPay() In the Employee hierarchy, getPay is implemented differently in each subclass and must therefore be a virtual method.

Abstract Classes An abstract class is a class that is never created on its own but instead serves as a common superclass for concrete classes that correspond to actual objects. In C++, any method that is always implemented by a concrete subclass is indicated by including = 0 before the semicolon on the prototype line, as follows: class Employee { virtual double getPay() }; class HourlyEmployee : public Employee { virtual double getPay(); }; class CommissionedEmployee : public Employee { virtual double getPay(); }; class SalariedEmployee : public Employee { virtual double getPay(); }; ; = 0

The Darwin Simulation Game Years ago, one of the 106B assignments was the Darwin game, which was played on a grid populated by “creatures” trying to “infect” other types. The standard creatures were: Rover, which tries to move forward, turning if blocked. Flytrap, which simply spins to the left. Food, which does nothing except wait to be eaten.

Rover, which tries to move forward, turning if blocked. Flytrap, which simply spins to the left. Food, which does nothing except wait to be eaten. The Darwin Simulation Game In the next generation: This Rover infects the Flytrap. This Rover turns randomly. This Flytrap infects the food. Other Flytraps turn left. Other Rovers move forward.

Specifying Creature Behavior The creatures in the Darwin game have different behaviors, which are specified by defining a method called step. The definition of the step method is different for each subclass: void Flytrap::step() { if (facingEnemy()) { infect(); } else { turnLeft(); } void Rover::step() { if (facingEnemy()) { infect(); } else if (isBlocked()) { if (random()) { turnLeft(); } else { turnRight(); } } else { move(); } void Food::step() { /* Empty */ } Because the definition of step is different in each subclass, this method must be virtual.

The Creature Hierarchy Rover Rover() virtual step() Creature Creature() virtual step() setImage( name ) move() turnLeft() turnRight() infect() facingWall() facingEnemy() facingSame() isBlocked() Flytrap Flytrap() virtual step() Food Food() virtual step()

Representing Graphical Shapes In CS 106A, you learned how to use the GObject hierarchy in the acm.graphics package, which looks something like this: GObject The gobjects.h interface includes all these classes. Chapter 19, however, implements just a few of them. GLineGRectGOval GRoundRectG3DRect GLabelGImageGArcGPolygon In C++, the most important thing to keep in mind is that you have to use pointers to these objects.

Exercise: Do Not Enter The British version of a “Do Not Enter” sign looks like this: Write a program that uses the stripped-down version of the gobjects.h that displays this symbol at the center of the window. The sizes of the components are given as constants in the starter file.

The GObject Hierarchy GObject GObject() setLocation( x, y ) move( dx, dy ) setColor( color ) virtual draw( gw ) GLine GLine( x 1, y 1, x 2, y 2 ) virtual draw( gw ) GOval GOval( x, y, width, height ) setFilled( flag ) virtual draw( gw ) GRect GRect( x, y, width, height ) setFilled( flag ) virtual draw( gw )

/* * File: gobjects.h * * This file defines a simple hierarchy of graphical objects. */ #ifndef _gobjects_h #define _gobjects_h #include #include "gwindow.h" /* * Class: GObject * * This class is the root of the hierarchy and encompasses all objects * that can be displayed in a window. Clients will use pointers to * a GObject rather than the GObject itself. */ class GObject { public: The gobjects.h Interface

/* * File: gobjects.h * * This file defines a simple hierarchy of graphical objects. */ #ifndef _gobjects_h #define _gobjects_h #include #include "gwindow.h" /* * Class: GObject * * This class is the root of the hierarchy and encompasses all objects * that can be displayed in a window. Clients will use pointers to * a GObject rather than the GObject itself. */ class GObject { public: /* * Method: setLocation * Usage: gobj->setLocation(x, y); * * Sets the x and y coordinates of gobj to the specified values. */ void setLocation(double x, double y); /* * Method: move * Usage: gobj->move(dx, dy); * * Adds dx and dy to the coordinates of gobj. */ void move(double x, double y); /* * Method: setColor * Usage: gobj->setColor(color); * * Sets the color of gobj. */ void setColor(std::string color); The gobjects.h Interface

/* * Method: setLocation * Usage: gobj->setLocation(x, y); * * Sets the x and y coordinates of gobj to the specified values. */ void setLocation(double x, double y); /* * Method: move * Usage: gobj->move(dx, dy); * * Adds dx and dy to the coordinates of gobj. */ void move(double x, double y); /* * Method: setColor * Usage: gobj->setColor(color); * * Sets the color of gobj. */ void setColor(std::string color); /* * Abstract method: draw * Usage: gobj->draw(gw); * * Draws the graphical object on the GraphicsWindow specified by gw. * This method is implemented by the specific GObject subclasses. */ virtual void draw(GWindow & gw) = 0; protected: /* The following methods and fields are available to the subclasses */ GObject(); /* Superclass constructor */ std::string color; /* The color of the object */ double x, y; /* The coordinates of the object */ }; The gobjects.h Interface

/* * Abstract method: draw * Usage: gobj->draw(gw); * * Draws the graphical object on the GraphicsWindow specified by gw. * This method is implemented by the specific GObject subclasses. */ virtual void draw(GWindow & gw) = 0; protected: /* The following methods and fields are available to the subclasses */ GObject(); /* Superclass constructor */ std::string color; /* The color of the object */ double x, y; /* The coordinates of the object */ }; /* * Subclass: GLine * * The GLine subclass represents a line segment on the window. */ class GLine : public GObject { public: /* * Constructor: GLine * Usage: GLine *lp = new GLine(x1, y1, x2, y2); * * Creates a line segment that extends from (x1, y1) to (x2, y2). */ GLine(double x1, double y1, double x2, double y2); /* Prototypes for the overridden virtual methods */ virtual void draw(GWindow & gw); private: double dx; /* Horizontal distance from x1 to x2 */ double dy; /* Vertical distance from y1 to y2 */ }; The gobjects.h Interface

/* * Subclass: GLine * * The GLine subclass represents a line segment on the window. */ class GLine : public GObject { public: /* * Constructor: GLine * Usage: GLine *lp = new GLine(x1, y1, x2, y2); * * Creates a line segment that extends from (x1, y1) to (x2, y2). */ GLine(double x1, double y1, double x2, double y2); /* Prototypes for the overridden virtual methods */ virtual void draw(GWindow & gw); private: double dx; /* Horizontal distance from x1 to x2 */ double dy; /* Vertical distance from y1 to y2 */ }; class GRect : public GObject { public: /* * Constructor: GRect * Usage: GRect *rp = new GRect(x, y, width, height); * * Creates a rectangle of the specified size and upper left corner at (x, y). */ GRect(double x, double y, double width, double height); /* * Method: setFilled * Usage: rp->setFilled(flag); * * Indicates whether the rectangle is filled. */ void setFilled(bool flag); virtual void draw(GWindow & gw); private: double width, height; /* Dimensions of the rectangle */ bool filled; /* True if the rectangle is filled */ }; The gobjects.h Interface

class GRect : public GObject { public: /* * Constructor: GRect * Usage: GRect *rp = new GRect(x, y, width, height); * * Creates a rectangle of the specified size and upper left corner at (x, y). */ GRect(double x, double y, double width, double height); /* * Method: setFilled * Usage: rp->setFilled(flag); * * Indicates whether the rectangle is filled. */ void setFilled(bool flag); virtual void draw(GWindow & gw); private: double width, height; /* Dimensions of the rectangle */ bool filled; /* True if the rectangle is filled */ }; class GOval : public GObject { public: /* * Constructor: GOval * Usage: GOval *op = new GOval(x, y, width, height); * * Creates an oval inscribed in the specified rectangle. */ GOval(double x, double y, double width, double height); /* * Method: setFilled * Usage: op->setFilled(flag); * * Indicates whether the oval is filled. */ void setFilled(bool flag); virtual void draw(GWindow & gw); private: double width, height; /* Dimensions of the bounding rectangle */ bool filled; /* True if the oval is filled */ }; The gobjects.h Interface

/* * Implementation notes: GObject class * * The constructor for the superclass sets all graphical objects to BLACK, * which is the default color. */ GObject::GObject() { setColor("BLACK"); } void GObject::setLocation(double x, double y) { this->x = x; this->y = y; } void GObject::move(double dx, double dy) { x += dx; y += dy; } void GObject::setColor(string color) { this->color = color; } Implementation of the GObject Class

/* * Implementation notes: GLine class * * The constructor for the GLine class has to change the specification * of the line from the endpoints passed to the constructor to the * representation that uses a starting point along with dx/dy values. */ GLine::GLine(double x1, double y1, double x2, double y2) { this->x = x1; this->y = y1; this->dx = x2 - x1; this->dy = y2 - y1; } void GLine::draw(GWindow & gw) { gw.setColor(color); gw.drawLine(x, y, x + dx, y + dy); } Implementation of the GLine Class

GRect::GRect(double x, double y, double width, double height) { this->x = x; this->y = y; this->width = width; this->height = height; filled = false; } void GRect::setFilled(bool flag) { filled = flag; } void GRect::draw(GWindow & gw) { gw.setColor(color); if (filled) { gw.fillRect(x, y, width, height); } else { gw.drawRect(x, y, width, height); } Implementation of the GRect Class

GOval::GOval(double x, double y, double width, double height) { this->x = x; this->y = y; this->width = width; this->height = height; filled = false; } void GOval::setFilled(bool flag) { filled = flag; } void GOval::draw(GWindow & gw) { gw.setColor(color); if (filled) { gw.fillOval(x, y, width, height); } else { gw.drawOval(x, y, width, height); } Implementation of the GOval Class

Calling Superclass Constructors When you call the constructor for an object, the constructor ordinarily calls the default constructor for the superclass, which is the one that takes no arguments. You can call a different version of the superclass constructor by adding an initializer list to the constructor header. This list consists of a colon followed either by a call to the superclass constructor or initializers for its variables. As an example, the following definition creates a GSquare subclass whose constructor takes the coordinates of the upper left corner and the size of the square: class GSquare : public GRect { GSquare(double x, double y, double size) : GRect(x, y, size, size) { /* Empty */ } };

The End