Chapter 14 Graph class design Bjarne Stroustrup www.stroustrup.com/Programming.

Slides:



Advertisements
Similar presentations
Chapter 16 Graphical User Interfaces
Advertisements

Chapter 12 A display model Bjarne Stroustrup
Chapter 8 Technicalities: Functions, etc. Bjarne Stroustrup
Chapter 13 Graphics classes Bjarne Stroustrup
Chapter 14 Graph class design Bjarne Stroustrup
Chapter 9 Technicalities: Classes, etc. Bjarne Stroustrup
Chapter 16 Graphical User Interfaces John Keyser’s Modifications of Slides by Bjarne Stroustrup
The C ++ Language BY Shery khan. The C++ Language Bjarne Stroupstrup, the language’s creator C++ was designed to provide Simula’s facilities for program.
Chapter 14 Graph class design John Keyser’s Modifications of Slides by Bjarne Stroustrup
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 13: Design of Classes CSCE : Set 13: Design of.
Classes and Object- Oriented... tMyn1 Classes and Object-Oriented Programming The essence of object-oriented programming is that you write programs in.
C++ Review. User Defined Types Built-in data types are simple. Specific problems may demand aggregate/more complex data types. – Ex: polygons, matrices,
Visual C++ Programming: Concepts and Projects Chapter 13A: Object-Oriented Programming (Concepts)
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Operator Overloading: indexing Useful to create range-checked structures: class four_vect { double stor[4]; // private member, actual contents of vector.
OOP Spring 2007 – Recitation 71 Object Oriented Programming Spring 2006 Recitation 8.
Liang, Introduction to Programming with C++, Second Edition, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 9 Objects and Classes.
C++ Training Datascope Lawrence D’Antonio Lecture 1 Quiz 1.
OOP Etgar 2008 – Recitation 71 Object Oriented Programming Etgar 2008 Recitation 7.
Operator Overloading: bounds-checked indexing Useful to create range-checked structures: class four_vect { double stor[4]; // private member, actual contents.
PolymorphismCS-2303, C-Term Polymorphism Hugh C. Lauer Adjunct Professor (Slides include materials from The C Programming Language, 2 nd edition,
Virtual Functions Junaed Sattar November 10, 2008 Lecture 10.
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.
1 Data Structures - CSCI 102 CS102 C++ Polymorphism Prof Tejada.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
1 Classes- Inheritance Multiple Inheritance It is possible to derive a new class from more than one base class. This is called Multiple Inheritance. Under.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 14 Graphics class design Hartmut Kaiser
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 12 A display model Hartmut Kaiser
Inheritance. Recall the plant that we defined earlier… class Plant { public: Plant( double theHeight ) : hasLeaves( true ), height (theHeight) { } Plant(
BIM313 – Advanced Programming Techniques Object-Oriented Programming 1.
C++ Review Classes and Object Oriented Programming Parasol Lab, Texas A&M University.
Chapter 13 Graphics classes Bjarne Stroustrup
Object Oriented Programming with C++/ Session 6 / 1 of 44 Multiple Inheritance and Polymorphism Session 6.
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
Copyright 2003 Scott/Jones Publishing Standard Version of Starting Out with C++, 4th Edition Chapter 13 Introduction to Classes.
CSCE 121: Introduction to Program Design and Concepts Dr. J. Michael Moore Spring 2015 Set 12: A Display Model 1 Based on slides created by Bjarne.
1 Inheritance. 2 Why use inheritance?  The most important aspect of inheritance is that it expresses a relationship between the new class and the base.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Chapter 9 Questions 1. What are the difference between constructors and member functions? 2. Design and implement a simple class as you want, with constructors.
1 Lecture 6: Polymorphism - The fourth pillar of OOP -
Operator Overloading: indexing Useful to create range-checked structures: class four_vect { double stor[4]; // private member, actual contents of vector.
Lecture 10 Concepts of Programming Languages Arne Kutzner Hanyang University / Seoul Korea.
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 12 A display model Hartmut Kaiser
Object-Oriented Programming Chapter Chapter
Slides adapted from: Bjarne Stroustrup, Programming – Principles and Practice using C++ Chapter 13 Graphics classes Hartmut Kaiser
ISBN Object-Oriented Programming Chapter Chapter
Copyright © 2005 Elsevier Object-Oriented Programming Control or PROCESS abstraction is a very old idea (subroutines!), though few languages provide it.
Chapter 14 Graph class design Bjarne Stroustrup
Object-Oriented Programming (OOP) What we did was: (Procedural Programming) a logical procedure that takes input data, processes it, and produces output.
Overview of C++ Polymorphism
Object Oriented Programming. OOP  The fundamental idea behind object-oriented programming is:  The real world consists of objects. Computer programs.
OBJECT ORIENTED PROGRAMMING. Design principles for organizing code into user-defined types Principles include: Encapsulation Inheritance Polymorphism.
1 Introduction to Object Oriented Programming Chapter 10.
Polymorphism and Virtual Functions One name many shapes behaviour Unit - 07.
Object-Oriented programming in C++ Classes as units of encapsulation Information Hiding Inheritance polymorphism and dynamic dispatching Storage management.
CSC241 Object-Oriented Programming (OOP) Lecture No. 17.
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.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.
ISBN Chapter 12 Support for Object-Oriented Programming.
Object-Oriented Programming Review 1. Object-Oriented Programming Object-Oriented Programming languages vary but generally all support the following features:
Chapter 14 Graph class design
Week 6 Object-Oriented Programming (2): Polymorphism
Chapter 13 Graphics classes
Chapter 14 Graph class design
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
Chapter 13 Graphics classes
Chapter 14 Graph class design
Overview of C++ Polymorphism
Chapter 14 Graph class design
Computer Science II for Majors
Presentation transcript:

Chapter 14 Graph class design Bjarne Stroustrup

Abstract We have discussed classes in previous lectures We have discussed classes in previous lectures Here, we discuss design of classes Here, we discuss design of classes Library design considerations Library design considerations Class hierarchies (object-oriented programming) Class hierarchies (object-oriented programming) Data hiding Data hiding 2Stroustrup/Programming/2015

Ideals Our ideal of program design is to represent the concepts of the application domain directly in code. Our ideal of program design is to represent the concepts of the application domain directly in code. If you understand the application domain, you understand the code, and vice versa. For example: If you understand the application domain, you understand the code, and vice versa. For example: Window – a window as presented by the operating system Window – a window as presented by the operating system Line – a line as you see it on the screen Line – a line as you see it on the screen Point – a coordinate point Point – a coordinate point Color – as you see it on the screen Color – as you see it on the screen Shape – what’s common for all shapes in our Graph/GUI view of the world Shape – what’s common for all shapes in our Graph/GUI view of the world The last example, Shape, is different from the rest in that it is a generalization. The last example, Shape, is different from the rest in that it is a generalization. You can’t make an object that’s “just a Shape” You can’t make an object that’s “just a Shape” 3Stroustrup/Programming/2015

Logically identical operations have the same name For every class, For every class, draw_lines() does the drawing draw_lines() does the drawing move(dx,dy) does the moving move(dx,dy) does the moving s.add(x) adds some x (e.g., a point) to a shape s. s.add(x) adds some x (e.g., a point) to a shape s. For every property x of a Shape, For every property x of a Shape, x() gives its current value and x() gives its current value and set_x() gives it a new value set_x() gives it a new value e.g., e.g., Color c = s.color(); s.set_color(Color::blue); 4Stroustrup/Programming/2015

Logically different operations have different names Lines ln; Point p1 {100,200}; Point p2 {200,300}; ln.add(p1,p2);// add points to ln (make copies) win.attach(ln);// attach ln to window Why not win.add(ln)? Why not win.add(ln)? add() copies information; attach() just creates a reference add() copies information; attach() just creates a reference we can change a displayed object after attaching it, but not after adding it we can change a displayed object after attaching it, but not after adding it 5 (100,200) (200,300) &ln ln: win: (100,200) p1: (200,300) p2: attach() add() Stroustrup/Programming/2015

Expose uniformly Data should be private Data should be private Data hiding – so it will not be changed inadvertently Data hiding – so it will not be changed inadvertently Use private data, and pairs of public access functions to get and set the data Use private data, and pairs of public access functions to get and set the data c.set_radius(12);// set radius to 12 c.set_radius(c.radius()*2);// double the radius (fine) c.set_radius(-9); // set_radius() could check for negative, // but doesn’t yet double r = c.radius();// returns value of radius c.radius = -9;// error: radius is a function (good!) c.r = -9;// error: radius is private (good!) Our functions can be private or public Our functions can be private or public Public for interface Public for interface Private for functions used only internally to a class Private for functions used only internally to a class 6Stroustrup/Programming/2015

What does “private” buy us? We can change our implementation after release We can change our implementation after release We don’t expose FLTK types used in representation to our users We don’t expose FLTK types used in representation to our users We could replace FLTK with another library without affecting user code We could replace FLTK with another library without affecting user code We could provide checking in access functions We could provide checking in access functions But we haven’t done so systematically (later?) But we haven’t done so systematically (later?) Functional interfaces can be nicer to read and use Functional interfaces can be nicer to read and use E.g., s.add(x) rather than s.points.push_back(x) E.g., s.add(x) rather than s.points.push_back(x) We enforce immutability of shape We enforce immutability of shape Only color and style change; not the relative position of points Only color and style change; not the relative position of points const member functions const member functions The value of this “encapsulation” varies with application domains The value of this “encapsulation” varies with application domains Is often most valuable Is often most valuable Is the ideal Is the ideal i.e., hide representation unless you have a good reason not to i.e., hide representation unless you have a good reason not to 7Stroustrup/Programming/2015

“Regular” interfaces Line ln {Point{100,200},Point{300,400}}; Mark m {Point{100,200}, 'x'};// display a single point as an 'x' Circle c {Point{200,200},250}; // Alternative (not supported): Line ln2 {x1, y1, x2, y2}; // integer arguments: from (x1,y1) to (x2,y2) // How about? (both supported): Rectangle s1 {Point{100,200},200,300}; // width==200 height==300 Rectangle s2 {Point{100,200},Point{200,300}}; // width==100 height==100 // but (an error): Rectangle s3 {100,200,200,300};// is 200,300 a point or a width plus a height? 8Stroustrup/Programming/2015

A library A collection of classes and functions meant to be used together A collection of classes and functions meant to be used together As building blocks for applications As building blocks for applications To build more such “building blocks” To build more such “building blocks” A good library models some aspect of a domain A good library models some aspect of a domain It doesn’t try to do everything It doesn’t try to do everything Our library aims at simplicity and small size for graphing data and for very simple GUI Our library aims at simplicity and small size for graphing data and for very simple GUI We can’t define each library class and function in isolation We can’t define each library class and function in isolation A good library exhibits a uniform style (“regularity”) A good library exhibits a uniform style (“regularity”) 9Stroustrup/Programming/2015

Class Shape All our shapes are “based on” the Shape class All our shapes are “based on” the Shape class E.g., a Polygon is a kind of Shape E.g., a Polygon is a kind of Shape 10 Shape Polygon Text Open_polyline EllipseCircle Marked_polyline Closed_polyline Line Mark Lines Marks Axis Function Rectangle Image Stroustrup/Programming/2015

Class Shape Shape is a base class Shape is a base class Defines what is common to all Shapes Defines what is common to all Shapes class Shape { public: void draw() const;// deal with color and draw lines virtual void move(int dx, int dy);// move the Shape: +=dx and +=dy void set_color(Color col); color color() const; // … }; Stroustrup/Programming/

Class Shape Shape ties our graphics objects to “the screen” Shape ties our graphics objects to “the screen” Window “knows about” Shapes Window “knows about” Shapes All our graphics objects are kinds of Shapes All our graphics objects are kinds of Shapes Shape is the class that deals with color and style Shape is the class that deals with color and style It has Color and Line_style members It has Color and Line_style members Shape can hold Points Shape can hold Points Shape has a basic notion of how to draw lines Shape has a basic notion of how to draw lines It just connects its Points It just connects its Points 12Stroustrup/Programming/2015

Class Shape Shape deals with color and style Shape deals with color and style It keeps its data private and provides access functions It keeps its data private and provides access functions void set_color(Color col); Color color() const; void set_style(Line_style sty); Line_style style() const; // … private: Color line_color; Line_style ls; 13Stroustrup/Programming/2015

Class Shape Shape stores Points Shape stores Points It keeps its data private and provides access functions It keeps its data private and provides access functions Point point(int i) const;// read-only access to points int number_of_points() const; // … protected: void add(Point p);// add p to points void add(Point p);// add p to points // … // …private: vector points;// not used by all shapes 14Stroustrup/Programming/2015

Class Shape Shape itself can access points directly: Shape itself can access points directly: void Shape::draw_lines() const// draw connecting lines { if (color().visible() && 1<points.size()) for (int i=1; i<points.size(); ++i) fl_line(points[i-1].x,points[i-1].y,points[i].x,points[i].y);} Others (incl. derived classes) use point() and number_of_points() Others (incl. derived classes) use point() and number_of_points() why? why? void Lines::draw_lines() const// draw a line for each pair of points { for (int i=1; i<number_of_points(); i+=2) fl_line(point(i-1).x, point(i-1).y, point(i).x, point(i).y); } 15Stroustrup/Programming/2015

Class Shape (basic idea of drawing) void Shape::draw() const // The real heart of class Shape (and of our graphics interface system) // called by Window (only) { // … save old color and style … // … set color and style for this shape… // … draw what is specific for this particular shape … // … Note: this varies dramatically depending on the type of shape … // … e.g. Text, Circle, Closed_polyline // … reset the color and style to their old values … } 16Stroustrup/Programming/2015

Class Shape (implementation of drawing) void Shape::draw() const // The real heart of class Shape (and of our graphics interface system) // called by Window (only) { Fl_Color oldc = fl_color();// save old color // there is no good portable way of retrieving the current style (sigh!) fl_color(line_color.as_int());// set color and style fl_line_style(ls.style(),ls.width()); draw_lines();// call the appropriate draw_lines() // a “virtual call” // here is what is specific for a “derived class” is done fl_color(oldc);// reset color to previous fl_line_style(0);// (re)set style to default } 17 Note! Stroustrup/Programming/2015

Class Shape – is abstract You can’t make a “plain” Shape You can’t make a “plain” Shapeprotected: Shape();// protected to make class Shape abstract For example Shape ss;// error: cannot construct Shape Protected means “can only be used from this class or from a derived class” Protected means “can only be used from this class or from a derived class” Instead, we use Shape as a base class Instead, we use Shape as a base class struct Circle : Shape {// “a Circle is a Shape” // … }; 18Stroustrup/Programming/2015

Class shape In class Shape In class Shape virtual void draw_lines() const; // draw the appropriate lines In class Circle In class Circle void draw_lines() const { /* draw the Circle */ } In class Text In class Text void draw_lines() const { /* draw the Text */ } void draw_lines() const { /* draw the Text */ } Circle, Text, and other classes Circle, Text, and other classes “Derive from” Shape “Derive from” Shape May “override” draw_lines() May “override” draw_lines() 19Stroustrup/Programming/2015

class Shape {// deals with color and style, and holds a sequence of lines public: void draw() const;// deal with color and call draw_lines() virtual void move(int dx, int dy); // move the shape +=dx and +=dy void set_color(Color col);// color access int color() const; // … style and fill_color access functions … Point point(int i) const;// (read-only) access to points int number_of_points() const; protected: Shape();// protected to make class Shape abstract void add(Point p);// add p to points virtual void draw_lines() const; // simply draw the appropriate lines private: vector points;// not used by all shapes Color lcolor;// line color Line_style ls;// line style Color fcolor;// fill color // … prevent copying … }; 20Stroustrup/Programming/2015

Display model completed 21 Circle draw_lines() Text draw_lines() Window Display Engine draw() our code make objects wait_for_button() Shape draw_lines() attach() Stroustrup/Programming/2015

Language mechanisms Most popular definition of object-oriented programming: Most popular definition of object-oriented programming: OOP == inheritance + polymorphism + encapsulation OOP == inheritance + polymorphism + encapsulation Base and derived classes// inheritance Base and derived classes// inheritance struct Circle : Shape { … }; struct Circle : Shape { … }; Also called “inheritance” Also called “inheritance” Virtual functions// polymorphism Virtual functions// polymorphism virtual void draw_lines() const; virtual void draw_lines() const; Also called “run-time polymorphism” or “dynamic dispatch” Also called “run-time polymorphism” or “dynamic dispatch” Private and protected// encapsulation Private and protected// encapsulation protected: Shape(); protected: Shape(); private: vector points; private: vector points; 22Stroustrup/Programming/2015

A simple class hierarchy We chose to use a simple (and mostly shallow) class hierarchy We chose to use a simple (and mostly shallow) class hierarchy Based on Shape Based on Shape 23 Shape Polygon Text Open_polyline EllipseCircle Marked_polyline Closed_polyline Line Mark Lines Marks Axis Function Rectangle Image Stroustrup/Programming/2015

Object layout The data members of a derived class are simply added at the end of its base class (a Circle is a Shape with a radius) The data members of a derived class are simply added at the end of its base class (a Circle is a Shape with a radius) 24 points line_color ls fcolor Shape: points line_color ls fcolor r Circle: Stroustrup/Programming/2015

Object layout Virtual function implementation Virtual function implementation 25 points line_color ls fcolor vptr Open_polyline: points line_color ls fcolor vptr r Circle: Stroustrup/Programming/2015 draw move draw move Cicle::draw_lines() { … } Shape::move() { … } Shape::draw_lines() { … }

Benefits of inheritance Interface inheritance Interface inheritance A function expecting a shape (a Shape&) can accept any object of a class derived from Shape. A function expecting a shape (a Shape&) can accept any object of a class derived from Shape. Simplifies use Simplifies use sometimes dramatically sometimes dramatically We can add classes derived from Shape to a program without rewriting user code We can add classes derived from Shape to a program without rewriting user code Adding without touching old code is one of the “holy grails” of programming Adding without touching old code is one of the “holy grails” of programming Implementation inheritance Implementation inheritance Simplifies implementation of derived classes Simplifies implementation of derived classes Common functionality can be provided in one place Common functionality can be provided in one place Changes can be done in one place and have universal effect Changes can be done in one place and have universal effect Another “holy grail” Another “holy grail” 26Stroustrup/Programming/2015

Access model A member (data, function, or type member) or a base can be A member (data, function, or type member) or a base can be Private, protected, or public Private, protected, or public 27Stroustrup/Programming/2015

Pure virtual functions Often, a function in an interface can’t be implemented Often, a function in an interface can’t be implemented E.g. the data needed is “hidden” in the derived class E.g. the data needed is “hidden” in the derived class We must ensure that a derived class implements that function We must ensure that a derived class implements that function Make it a “pure virtual function” (=0) Make it a “pure virtual function” (=0) This is how we define truly abstract interfaces (“pure interfaces”) This is how we define truly abstract interfaces (“pure interfaces”) struct Engine {// interface to electric motors // no data // (usually) no constructor virtual double increase(int i) =0;// must be defined in a derived class // … virtual ~Engine();// (usually) a virtual destructor }; Engine eee;// error: Collection is an abstract class Stroustrup/Programming/201528

Pure virtual functions A pure interface can then be used as a base class A pure interface can then be used as a base class Constructors and destructors will be described in detail in chapters Constructors and destructors will be described in detail in chapters Class M123 : public Engine {// engine model M123 // representation public: M123();// construtor: initialization, acquire resources double increase(int i) override { /* … */ }// overrides Engine ::increase // … ~M123();// destructor: cleanup, release resources }; M123 window3_control;// M123 window3_control;// OK Stroustrup/Programming/201529

Technicality: Copying If you don’t know how to copy an object, prevent copying If you don’t know how to copy an object, prevent copying Abstract classes typically should not be copied Abstract classes typically should not be copied class Shape { // … Shape(const Shape&) = delete;// don’t “copy construct” Shape& operator=(const Shape&) = delete;// don’t “copy assign” }; void f(Shape& a) { Shape s2 = a;// error: no Shape “copy constructor” (it’s deleted) a = s2;// error: no Shape “copy assignment” (it’s deleted) } Stroustrup/Programming/201530

Prevent copying C++98 style If you don’t know how to copy an object, prevent copying If you don’t know how to copy an object, prevent copying Abstract classes typically should not be copied Abstract classes typically should not be copied class Shape { // … private: Shape(const Shape&);// don’t “copy construct” Shape& operator=(const Shape&);// don’t “copy assign” }; void f(Shape& a) { Shape s2 = a;// error: no Shape “copy constructor” (it’s private) a = s2;// error: no Shape “copy assignment” (it’s private) } Stroustrup/Programming/201531

Technicality: Overriding To override a virtual function, you need To override a virtual function, you need A virtual function A virtual function Exactly the same name Exactly the same name Exactly the same type Exactly the same type struct B { void f1();// not virtual virtual void f2(char); virtual void f3(char) const; virtual void f4(int); }; Stroustrup/Programming/ struct D : B { void f1();// doesn’t override void f2(int); // doesn’t override void f3(char); // doesn’t override void f4(int);// overrides };

Technicality: Overriding To override a virtual function, you need To override a virtual function, you need A virtual function A virtual function Exactly the same name Exactly the same name Exactly the same type Exactly the same type struct B { void f1();// not virtual virtual void f2(char); virtual void f3(char) const; virtual void f4(int); }; Stroustrup/Programming/ struct D : B { void f1() override;// error void f2(int) override; // error void f3(char) override; // error void f4(int) override;// OK };

Technicality: Overriding To invoke a virtual function, you need To invoke a virtual function, you need A reference, or A reference, or A pointer A pointer D d1; B& bref = d1; // d1 is a D, and a D is a B, so d1 is a B bref.f4(2); // calls D::f4(2) on d1 since bref names a D // pointers are in chapter 17 B *bptr = &d1; // d1 is a D, and a D is a B, so d1 is a B bptr->f4(2); // calls D::f4(2) on d1 since bptr points to a D Stroustrup/Programming/201534

Next lecture Graphing functions and data Graphing functions and data 35Stroustrup/Programming/2015