SlideShare a Scribd company logo
Chapter 14 Graph class design Bjarne Stroustrup www.stroustrup.com/Programming
Abstract We have discussed classes in previous lectures Here, we discuss design of classes Library design considerations Class hierarchies (object-oriented programming) Data hiding  Stroustrup/Programming
Ideals 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: Window  – a window as presented by the operating system Line  – a line as you see it on the screen Point  – a coordinate point Color  – as you see it on the screen  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. You can’t make an object that’s “just a Shape” Stroustrup/Programming
Logically identical operations have the same name For every class, draw_lines()  does the drawing move(dx,dy)  does the moving s.add(x)  adds some  x  ( e.g. , a point) to a shape  s . For every property  x  of a Shape, x()  gives its current value and set_x()  gives it a new value e.g., Color c = s.color(); s.set_color(Color::blue); Stroustrup/Programming
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) ? add()  copies information;  attach()  just creates a reference we can change a displayed object after attaching it, but not after adding it (100,200) p1: (200,300) p2: attach() add() Stroustrup/Programming (100,200) (200,300) &ln ln: win:
Expose uniformly Data should be private Data hiding – so it will not be changed inadvertently 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 Public for interface Private for functions used only internally to a class Stroustrup/Programming
What does “private” buy us? We can change our implementation after release 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 provide checking in access functions But we haven’t done so systematically (later?) Functional interfaces can be nicer to read and use E.g.,  s.add(x)  rather than  s.points.push_back(x) We enforce immutability of shape Only color and style change; not the relative position of points const  member functions The value of this “encapsulation” varies with application domains Is often most valuable Is the ideal i.e., hide representation unless you have a good reason not to Stroustrup/Programming
“ 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);   //   from (x1,y1) to (x2,y2) //   How about? (not supported): Square s1(Point(100,200),200,300);  //  width==200 height==300 Square s2(Point(100,200),Point(200,300)); //  width==100 height==100 Square s3(100,200,200,300);  //  is 200,300 a point  or a width plus a height? Stroustrup/Programming
A library A collection of classes and functions meant to be used together As building blocks for applications To build more such “building blocks” A good library models some aspect of a domain  It doesn’t try to do everything 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 A good library exhibits a uniform style (“regularity”) Stroustrup/Programming
Class Shape All our shapes are “based on” the Shape class E.g., a  Polygon  is a kind of  Shape Rectangle Image Stroustrup/Programming Shape Polygon Text Open_polyline Ellipse Circle Marked_polyline Closed_polyline Line Mark Lines Marks Axis Function
Class Shape  – is abstract You can’t make a “plain” Shape protected: Shape(); //  protected to make class Shape abstract For example Shape ss; //   error: cannot construct Shape Protected means “can only be used from a derived class” Instead, we use Shape as a base class struct Circle : Shape { //  “a Circle is a Shape” //  … };  Stroustrup/Programming
Class Shape Shape  ties our graphics objects to “the screen” Window  “knows about”  Shape s All our graphics objects are kinds of  Shape s Shape  is the class that deals with color and style It has  Color  and  Line_style  members  Shape  can hold  Point s  Shape  has a basic notion of how to draw lines It just connects its  Point s Stroustrup/Programming
Class Shape Shape deals with color and style 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; Stroustrup/Programming
Class Shape Shape  stores  Point s 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   //  … private: vector<Point> points; //  not used by all shapes Stroustrup/Programming
Class Shape 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() 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); } Stroustrup/Programming
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 … } Stroustrup/Programming
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 } Note! Stroustrup/Programming
Class shape In class  Shape virtual void draw_lines() const;  //  draw the appropriate lines In class  Circle void draw_lines() const { /*  draw the Circle  */ } In class  Text void draw_lines() const { /*  draw the Text  */ } Circle ,  Text , and other classes “ Derive from”  Shape May “override”  draw_lines() Stroustrup/Programming
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<Point> points; //  not used by all shapes Color  lcolor; //  line color Line_style  ls; //  line style Color  fcolor; //  fill color //  … prevent copying … }; Stroustrup/Programming
Display model completed attach() Stroustrup/Programming Circle draw_lines() Text draw_lines() Window Display Engine draw() draw() draw() our code make objects wait_for_button() Shape Shape draw_lines() draw_lines()
Language mechanisms Most popular definition of object-oriented programming:  OOP == inheritance + polymorphism + encapsulation Base and derived classes //  inheritance struct Circle : Shape { … }; Also called “inheritance” Virtual functions //  polymorphism virtual void draw_lines() const; Also called “run-time polymorphism” or “dynamic dispatch” Private and protected //  encapsulation protected: Shape(); private: vector<Point> points; Stroustrup/Programming
A simple class hierarchy We chose to use a simple (and mostly shallow) class hierarchy Based on Shape Rectangle Image Stroustrup/Programming Shape Polygon Text Open_polyline Ellipse Circle Marked_polyline Closed_polyline Line Mark Lines Marks Axis Function
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) Stroustrup/Programming points line_color ls Shape: points  line_color ls ---------------------- r Circle:
Benefits of inheritance Interface inheritance A function expecting a shape (a  Shape& ) can accept any object of a class derived from Shape. Simplifies use sometimes dramatically 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 Implementation inheritance Simplifies implementation of derived classes Common functionality can be provided in one place Changes can be done in one place and have universal effect Another “holy grail” Stroustrup/Programming
Access model A member (data, function, or type member) or a base can be Private, protected, or public Stroustrup/Programming
Pure virtual functions Often, a function in an interface can’t be implemented E.g. the data needed is “hidden” in the derived class We must ensure that a derived class implements that function Make it a “pure virtual function” ( =0 ) 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
Pure virtual functions A pure interface can then be used as a base class Constructors and destructors will be describe d in detail in chapters  17-19 Class M123 : public Engine { //  engine model M123 //  representation public: M123(); //  construtor:  initialization, acquire resources double increase(int i) { /*  …  */ } //  overrides Engine ::increase //  … ~M123(); //  destructor: cleanup, release resources }; M123 window3_control; //  OK Stroustrup/Programming
Technicality: Copying If you don’t know how to copy an object, prevent copying 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
Technicality: Overriding To override a virtual function, you need A virtual function Exactly the same name Exactly the same type struct B { void f1(); //  not virtual void f2(char); void f3(char) const; 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 };
Next lecture Graphing functions and data Stroustrup/Programming

More Related Content

PPT
13 Graph Classes
PPT
13 graph classes_2
PDF
L4
PDF
Auto cad tutorial
PDF
Auto cad commands.
PDF
Dotnet unit 4
PPTX
Autocad chapter 4 for mobile use.
PDF
Auto cad manual
13 Graph Classes
13 graph classes_2
L4
Auto cad tutorial
Auto cad commands.
Dotnet unit 4
Autocad chapter 4 for mobile use.
Auto cad manual

What's hot (20)

PPT
31 uml
PPTX
Autocad electrical
PDF
TUTORIAL AUTO CAD 3D
PPTX
CIV1900 Matlab - Plotting & Coursework
PDF
Auto cad shortcuts
PPTX
Presentation On Auto Cad
PPTX
Eg5 n
PDF
AutoCad Basic tutorial
PDF
Cad 003
PDF
Unit-2 raster scan graphics,line,circle and polygon algorithms
PPTX
Auto cad
PDF
Auto cad shortcuts___ & Commands booklet. best choice!!!
PDF
Introduction to autocad_lt
PDF
Class program and uml in c++
PPT
Visula C# Programming Lecture 7
DOCX
Practical work 2
PDF
PPT
Lecture 3
DOCX
Practical work 3
PDF
Acad commands
31 uml
Autocad electrical
TUTORIAL AUTO CAD 3D
CIV1900 Matlab - Plotting & Coursework
Auto cad shortcuts
Presentation On Auto Cad
Eg5 n
AutoCad Basic tutorial
Cad 003
Unit-2 raster scan graphics,line,circle and polygon algorithms
Auto cad
Auto cad shortcuts___ & Commands booklet. best choice!!!
Introduction to autocad_lt
Class program and uml in c++
Visula C# Programming Lecture 7
Practical work 2
Lecture 3
Practical work 3
Acad commands
Ad

Viewers also liked (8)

PPTX
Uml Presentation
PPTX
Uml with detail
PDF
UML Design Class Diagrams (2014)
PDF
Types of UML diagrams
PPT
UML- Unified Modeling Language
PPTX
Uml Presentation
PPT
Uml diagrams
PPT
UML Diagrams
Uml Presentation
Uml with detail
UML Design Class Diagrams (2014)
Types of UML diagrams
UML- Unified Modeling Language
Uml Presentation
Uml diagrams
UML Diagrams
Ad

Similar to 14 class design (1) (20)

PPT
Some examples of shapes are Lines, Polygons, Axes, and Text
PDF
Computer Graphics Concepts
PPT
C++ Inheritance
PPTX
Learn Creative Coding: Begin Programming with the Processing Language
PPTX
Learn Creative Coding: Begin Programming with the Processing Language
PDF
Intake 37 6
PPT
Applets - lev' 2
PPS
C++ Language
PPT
Synapseindia dot net development
PDF
Introduction to Coding
PDF
L10
PPT
JAVA OOP
PDF
PDF
Intake 38 6
PDF
Functions And Header Files In C++ | Bjarne stroustrup
PDF
Im having trouble figuring out how to code these sections for an a.pdf
PPT
Visula C# Programming Lecture 2
PPT
Client Side Programming with Applet
PPT
Week 10-classdiagrams.pptdddddddddddddddddddddddddddd
PPT
Basics of objective c
Some examples of shapes are Lines, Polygons, Axes, and Text
Computer Graphics Concepts
C++ Inheritance
Learn Creative Coding: Begin Programming with the Processing Language
Learn Creative Coding: Begin Programming with the Processing Language
Intake 37 6
Applets - lev' 2
C++ Language
Synapseindia dot net development
Introduction to Coding
L10
JAVA OOP
Intake 38 6
Functions And Header Files In C++ | Bjarne stroustrup
Im having trouble figuring out how to code these sections for an a.pdf
Visula C# Programming Lecture 2
Client Side Programming with Applet
Week 10-classdiagrams.pptdddddddddddddddddddddddddddd
Basics of objective c

More from Satyam Gupta (20)

PPT
Xerophytes
PPT
Viruses 001
PPT
Viruses
PPT
Symbiosis3
PPT
Symbiosis2
PPT
Symbiosis
PPT
What is ecology
PPT
Core sub math_att_4pythagoreantheorem
PPT
Circle theorems
PPT
Circles
PPT
Circles (4)
PPT
Circles (3)
PPT
Circles (2)
PPT
Circle
PPT
2006 7 3
PPT
14 class design
PPT
12.215.lec04
PPT
6.1 circles---day-28-1
PPT
Cummason
PPT
Physics chpt18
Xerophytes
Viruses 001
Viruses
Symbiosis3
Symbiosis2
Symbiosis
What is ecology
Core sub math_att_4pythagoreantheorem
Circle theorems
Circles
Circles (4)
Circles (3)
Circles (2)
Circle
2006 7 3
14 class design
12.215.lec04
6.1 circles---day-28-1
Cummason
Physics chpt18

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
NewMind AI Weekly Chronicles - August'25-Week II
PPTX
Tartificialntelligence_presentation.pptx
PPTX
SOPHOS-XG Firewall Administrator PPT.pptx
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Approach and Philosophy of On baking technology
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Encapsulation theory and applications.pdf
PPTX
Spectroscopy.pptx food analysis technology
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
MIND Revenue Release Quarter 2 2025 Press Release
Per capita expenditure prediction using model stacking based on satellite ima...
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
NewMind AI Weekly Chronicles - August'25-Week II
Tartificialntelligence_presentation.pptx
SOPHOS-XG Firewall Administrator PPT.pptx
Advanced methodologies resolving dimensionality complications for autism neur...
Spectral efficient network and resource selection model in 5G networks
Approach and Philosophy of On baking technology
Reach Out and Touch Someone: Haptics and Empathic Computing
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Encapsulation theory and applications.pdf
Spectroscopy.pptx food analysis technology
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Big Data Technologies - Introduction.pptx
Electronic commerce courselecture one. Pdf
Building Integrated photovoltaic BIPV_UPV.pdf
Digital-Transformation-Roadmap-for-Companies.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
MIND Revenue Release Quarter 2 2025 Press Release

14 class design (1)

  • 1. Chapter 14 Graph class design Bjarne Stroustrup www.stroustrup.com/Programming
  • 2. Abstract We have discussed classes in previous lectures Here, we discuss design of classes Library design considerations Class hierarchies (object-oriented programming) Data hiding Stroustrup/Programming
  • 3. Ideals 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: Window – a window as presented by the operating system Line – a line as you see it on the screen Point – a coordinate point Color – as you see it on the screen 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. You can’t make an object that’s “just a Shape” Stroustrup/Programming
  • 4. Logically identical operations have the same name For every class, draw_lines() does the drawing move(dx,dy) does the moving s.add(x) adds some x ( e.g. , a point) to a shape s . For every property x of a Shape, x() gives its current value and set_x() gives it a new value e.g., Color c = s.color(); s.set_color(Color::blue); Stroustrup/Programming
  • 5. 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) ? add() copies information; attach() just creates a reference we can change a displayed object after attaching it, but not after adding it (100,200) p1: (200,300) p2: attach() add() Stroustrup/Programming (100,200) (200,300) &ln ln: win:
  • 6. Expose uniformly Data should be private Data hiding – so it will not be changed inadvertently 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 Public for interface Private for functions used only internally to a class Stroustrup/Programming
  • 7. What does “private” buy us? We can change our implementation after release 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 provide checking in access functions But we haven’t done so systematically (later?) Functional interfaces can be nicer to read and use E.g., s.add(x) rather than s.points.push_back(x) We enforce immutability of shape Only color and style change; not the relative position of points const member functions The value of this “encapsulation” varies with application domains Is often most valuable Is the ideal i.e., hide representation unless you have a good reason not to Stroustrup/Programming
  • 8. “ 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); // from (x1,y1) to (x2,y2) // How about? (not supported): Square s1(Point(100,200),200,300); // width==200 height==300 Square s2(Point(100,200),Point(200,300)); // width==100 height==100 Square s3(100,200,200,300); // is 200,300 a point or a width plus a height? Stroustrup/Programming
  • 9. A library A collection of classes and functions meant to be used together As building blocks for applications To build more such “building blocks” A good library models some aspect of a domain It doesn’t try to do everything 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 A good library exhibits a uniform style (“regularity”) Stroustrup/Programming
  • 10. Class Shape All our shapes are “based on” the Shape class E.g., a Polygon is a kind of Shape Rectangle Image Stroustrup/Programming Shape Polygon Text Open_polyline Ellipse Circle Marked_polyline Closed_polyline Line Mark Lines Marks Axis Function
  • 11. Class Shape – is abstract You can’t make a “plain” Shape protected: Shape(); // protected to make class Shape abstract For example Shape ss; // error: cannot construct Shape Protected means “can only be used from a derived class” Instead, we use Shape as a base class struct Circle : Shape { // “a Circle is a Shape” // … }; Stroustrup/Programming
  • 12. Class Shape Shape ties our graphics objects to “the screen” Window “knows about” Shape s All our graphics objects are kinds of Shape s Shape is the class that deals with color and style It has Color and Line_style members Shape can hold Point s Shape has a basic notion of how to draw lines It just connects its Point s Stroustrup/Programming
  • 13. Class Shape Shape deals with color and style 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; Stroustrup/Programming
  • 14. Class Shape Shape stores Point s 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 // … private: vector<Point> points; // not used by all shapes Stroustrup/Programming
  • 15. Class Shape 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() 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); } Stroustrup/Programming
  • 16. 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 … } Stroustrup/Programming
  • 17. 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 } Note! Stroustrup/Programming
  • 18. Class shape In class Shape virtual void draw_lines() const; // draw the appropriate lines In class Circle void draw_lines() const { /* draw the Circle */ } In class Text void draw_lines() const { /* draw the Text */ } Circle , Text , and other classes “ Derive from” Shape May “override” draw_lines() Stroustrup/Programming
  • 19. 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<Point> points; // not used by all shapes Color lcolor; // line color Line_style ls; // line style Color fcolor; // fill color // … prevent copying … }; Stroustrup/Programming
  • 20. Display model completed attach() Stroustrup/Programming Circle draw_lines() Text draw_lines() Window Display Engine draw() draw() draw() our code make objects wait_for_button() Shape Shape draw_lines() draw_lines()
  • 21. Language mechanisms Most popular definition of object-oriented programming: OOP == inheritance + polymorphism + encapsulation Base and derived classes // inheritance struct Circle : Shape { … }; Also called “inheritance” Virtual functions // polymorphism virtual void draw_lines() const; Also called “run-time polymorphism” or “dynamic dispatch” Private and protected // encapsulation protected: Shape(); private: vector<Point> points; Stroustrup/Programming
  • 22. A simple class hierarchy We chose to use a simple (and mostly shallow) class hierarchy Based on Shape Rectangle Image Stroustrup/Programming Shape Polygon Text Open_polyline Ellipse Circle Marked_polyline Closed_polyline Line Mark Lines Marks Axis Function
  • 23. 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) Stroustrup/Programming points line_color ls Shape: points line_color ls ---------------------- r Circle:
  • 24. Benefits of inheritance Interface inheritance A function expecting a shape (a Shape& ) can accept any object of a class derived from Shape. Simplifies use sometimes dramatically 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 Implementation inheritance Simplifies implementation of derived classes Common functionality can be provided in one place Changes can be done in one place and have universal effect Another “holy grail” Stroustrup/Programming
  • 25. Access model A member (data, function, or type member) or a base can be Private, protected, or public Stroustrup/Programming
  • 26. Pure virtual functions Often, a function in an interface can’t be implemented E.g. the data needed is “hidden” in the derived class We must ensure that a derived class implements that function Make it a “pure virtual function” ( =0 ) 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
  • 27. Pure virtual functions A pure interface can then be used as a base class Constructors and destructors will be describe d in detail in chapters 17-19 Class M123 : public Engine { // engine model M123 // representation public: M123(); // construtor: initialization, acquire resources double increase(int i) { /* … */ } // overrides Engine ::increase // … ~M123(); // destructor: cleanup, release resources }; M123 window3_control; // OK Stroustrup/Programming
  • 28. Technicality: Copying If you don’t know how to copy an object, prevent copying 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
  • 29. Technicality: Overriding To override a virtual function, you need A virtual function Exactly the same name Exactly the same type struct B { void f1(); // not virtual void f2(char); void f3(char) const; 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 };
  • 30. Next lecture Graphing functions and data Stroustrup/Programming