1 data structures - csci 102 cs102 c++ composition & inheritance prof tejada

36
1 Data Structures - CSCI 102 CS102 C++ Composition & Inheritance Prof Tejada

Upload: jody-collins

Post on 27-Dec-2015

218 views

Category:

Documents


1 download

TRANSCRIPT

1

Data Structures - CSCI 102

CS102C++ Composition &

Inheritance

Prof Tejada

A car is built from a frame, transmission, tires, steeringwheel, etc.

In the real world, complex objects are built from smaller,simpler objects

3

Data Structures - CSCI 102

Copyright © William C. Cheng

Object Composition

A computer is built from a CPU, a hard drive, a powersupply, RAM, etc.

Object composition is the process of creating more complexobjects from simple ones

Use classes as member variables in other classesBecomes a "Has-A" relationship

e.g. A car "Has-A" steering wheel

It keeps your objects simple...an individual class shouldfocus on doing ONE thing well

Why should we use composition?

4

Data Structures - CSCI 102

Copyright © William C. Cheng

Composition

More complex objects don’t need to know the details ofwhat other objects are doing

Destroying the complex object means destroying all theobjects it contains

Composition usually implies ownership

Making objects self-contained and single-purposepromotes reusability

Composition without ownership (a.k.a. Aggregation)Destroying the complex object does not destroy all theobjects it contains

A creature in a videogameHas a name and hit points

5

Data Structures - CSCI 102

Copyright © William C. Cheng

Composition Example

We’ve already created a class to handle physical locations(remember "Point"?)

Has a physical location on a grid

class Creature {string name;int hp;Point location;

};

In the real world, complex objects share many attributeswith similar objects

6

Data Structures - CSCI 102

Copyright © William C. Cheng

Object Inheritance

A manager and a programmer both have a name, asalary, a job title, etc. They are both types of employees.

Object inheritance is the process of creating more complexobjects by acquiring the attributes and behaviors ofexisting ones

Create new classes from existing classesA "Base" class (a.k.a. Superclass)A "Derived" class (a.k.a. Subclass)

Becomes an "Is-A" relationshipe.g. A programmer "Is-An" employee

Both Managers & Programmers have a salary, phone #, etc.Managers may also have a list of people they manageProgrammers may also have a list of languages theyknow

7

Copyright © William C. Cheng

Data Structures - CSCI 102

InheritanceObject Inheritance can always be viewed as a tree structure

Derived classes inherit all data/functions from theirparent

Employee

Manager Programmer

Data Structures - CSCI 102

InheritanceObject Inheritance can be many levels deep

Shape

Triangle Rectangle

Square

8

Copyright © William C. Cheng

Data Structures - CSCI 102

InheritanceYou’ve already been using some objects that use lots ofinheritance (e.g. cin, cout, stringstream)

cout/cerr/clog

<iostream>

cin

<ostream>

<streambuf>

from www.cplusplus.com

9

Copyright © William C. Cheng

<istream>

istream

iostream

ostream

streambuf

<fstream>

ifstream

fstream

ofstream

filebuf

<sstream>

istringstream

stringstream

ostringstream

stringbuf

<ios>

ios_base

ios

Our Manager and Programmer classes wouldprobably have a lot in common

Why should we use inheritance?Code Reuse (Don’t repeat code!)

10

Data Structures - CSCI 102

Copyright © William C. Cheng

Inheritance

Directly reuse existing code and just tack on thefeatures you want (or hide those you don’t)

SpecializationTake existing objects and create related objects witha more finely-honed purpose

Behavior OveriddingDerived classes can redefine behaviors from thebase class implementation

Polymorphism

Define a base class "Shape"

11

Data Structures - CSCI 102

Copyright © William C. Cheng

Inheritance Example

class Shape {private:

Point center;public:

Shape(Point c);Shape(int x, int y);Point getCenter() const;void setCenter(Point c);void print() const;

};

Define a derived class "Triangle"

12

Data Structures - CSCI 102

Copyright © William C. Cheng

Inheritance Example

class Triangle : public Shape {private:

int base;int height;

public:Triangle(int b, int h);int getHeight() const;void setHeight(int h);int getBase() const;void setBase(int b);

};

// This won’t compileTriangle::Triangle(int h, int b, Point c): height(h), base(b), center(c) { }

The initialization list can only set the values of variablesin the current class!

When we instantiate a Triangle, how do we set the"Point center" in Shape?

13

Data Structures - CSCI 102

Copyright © William C. Cheng

Inheritance: Superclass Constructor

Basic initialization lists do NOT work

Initializing Shape’s variables in Triangle is a BAD idea andwill NOT always work (don’t want to skip calling the Shapeconstructor)

// This won’t compileTriangle::Triangle(int h, int b, Point c){ height = h; base = b; center = c; }

Triangle::Triangle(int h, int b, Point c): Shape(c), height(h), base(b) { }

We can use an initialization list to call a Shape (base class)constructor from a Triangle (derived class) constructor

14

Data Structures - CSCI 102

Copyright © William C. Cheng

Inheritance: Superclass Constructor

Triangle::Triangle(int h, int b, int x, int y): Shape(x,y), height(h), base(b) { }

The constructor of "Shape: is called before theconstructor of "triangle"

The superclass constructor will ALWAYS be called beforethe subclass constructor

15

Data Structures - CSCI 102

Copyright © William C. Cheng

Inheritance: Order of Creation/Destruction

The subclass can be dependent on data in thesuperclassCreate the inheritance tree from the root downward

Destroy the inheritance tree from the leaves upward

The subclass destructor will ALWAYS be called before thesuperclass destructor

Member data can be directly accessed by everyonepublic

16

Data Structures - CSCI 102

Copyright © William C. Cheng

Inheritance: Access Specifiers

Member data can only be accessed within the class thatcontains it. Subclasses cannot access superclassprivate data!

private

Member data can only be accessed within the class thatcontains it OR within its subclasses

protected

Triangle can’t modify "Point center" by default!

Redefine a base class "Shape" with a protected member

17

Data Structures - CSCI 102

Copyright © William C. Cheng

Inheritance Example

class Shape {protected:

//Shape and Triangle can access!Point center;

public:Shape(Point center);Shape(int x, int y);Point getCenter() const;void setCenter(Point c);void print() const;

};

You can add methods to your derived class just like youwould any other class

18

Data Structures - CSCI 102

Copyright © William C. Cheng

Making Derived Class Methods

class Triangle : public Shape {...

double getArea() const;};

Shape s;// does not compiledouble a = s.getArea();

Derived class methods are NOT visible in the base class

Subclass methods have the ability to overload and redefinesuperclass methods

19

Data Structures - CSCI 102

Copyright © William C. Cheng

Redefining Superclass Methods

class Shape {...

void print() const;};

class Triangle : public Shape {...

//must be identical to Shape’s to override!void print() const;

};

Compiler starts at the bottom of the inheritance tree andwalks up it looking for a method

Subclass methods have the ability to overload and redefinesuperclass methods, but can also call the original method

20

Data Structures - CSCI 102

Copyright © William C. Cheng

Redefining Superclass Methods

void Shape::print() const {cout << "I am a shape!" << endl;

}

void Triangle::print() const {//call superclass’ printShape::print();

cout << "I am a triangle!" << endl;}

Actually, anyone can call Shape::print() since it’s apublic member function of ShapeIt’s just like a regular function

Subclasses can redefine some superclass visibility

21

Data Structures - CSCI 102

Copyright © William C. Cheng

Show/Hide Superclass Methods

class Shape {public:

Point getCenter() const;protected:

void hiddenPrint() const;};

class Triangle : public Shape {public:

//make this visibleShape::hiddenPrint;

private://hide this from everyoneShape::getCenter;

};

22

Scanner Printer

Data Structures - CSCI 102

Multiple InheritanceA single class is actually allowed to derive from multipleclasses at once

Not used often. It gets confusing/complicated fast.

PoweredDevice

Copier

In practice, the only time you can do multipleinheritance is when you inherit from Interfaces(will talk about in a couple of lectures)

Copyright © William C. Cheng

23

Data Structures - CSCI 102

PolymorphismWhat is polymorphism?

The ability of an object of one type to appear and beused like an object of a different type

Remember our Shape and Triangle classes?Based on inheritance, Triange Is-A Shape so...We can actually pass Triangles around as Shapes!

Triangle t(5,5,15,20);Shape tval = t;Shape &tref = t;Shape *tptr = &t;Shape *tptr2 = new Triangle(1,2,55,62);

You can write very advanced code with polymorphismWrite algorithms & frameworks that manipulate base classCan even write code for subclasses that hasn’t

been realized or designed!Copyright © William C. Cheng

24

Data Structures - CSCI 102

Copyright © William C. Cheng

CS102Extra Slides

Bill Cheng

http://merlot.usc.edu/cs102-s12

Data Structures - CSCI 102

shape.h/** 1)* 2)*** 3)** 4)* 5)

Create a class Shape.*Protected* member Point center. This is so that asubclass can access the center. Use "point.h" and"point.cpp" from previous lecture.In the overloaded constructor use constructorinitialization list.Add accessor and mutator.Add print() member function.

*/

25

Copyright © William C. Cheng

26

Data Structures - CSCI 102

Copyright © William C. Cheng

shape.h#ifndef SHAPE_H_#define SHAPE_H_

#include "point.h"

class Shape{

protected:Point center;

public:Shape(Point pt)

: Point(pt) //call the Point class default constructor{ }

Shape(int x, int y): Point(x,y) //call the Point class overloaded constructor{ }

Point getCenter() const { return center; }void setCenter(Point p) { center = p; }

void print() const{

std::cout << "Shape located at " << center << std::endl;}

};

#endif

Data Structures - CSCI 102

triangle.h/** 1)* 2)* 3)** 4)* 5)

Create a class Triangle which is a subclass of Shape.Private members base (int) and height (int).In the overloaded constructor, calls parent class’sconstructor, set base and height.Add accessors and mutators.Add print() member function.

*/

27

Copyright © William C. Cheng

28

Data Structures - CSCI 102

triangle.h#ifndef TRIANGLE_H_#define TRIANGLE_H_

#include "point.h"#include "shape.h"

class Triangle : public Shape{

private:int base;int height;

public:Triangle(int b, int h, Point pt): Shape(pt), base(b), height(h) { }Triangle(int b, int h, int x, int y) : Shape(x,y){ base = b; height = h; }

int getBase() const {int getHeight() constvoid setBase(int b) {void setHeight(int h)

return base; }{ return height; }base = b; }{ height = h; }

void print() const{ std::cout << "Triangle located at "

<< center << std::endl;}

};

#endifCopyright © William C. Cheng

Data Structures - CSCI 102

inherit_main.cpp/*

* 1)* 2)* 3)* 4)* 5)** 6)** 7)***

Create a Shape with centre at (100,100), print it.Create a Triangle with centre at (5,5).Cannot create a Shape s2;How about creating a Shape s2=t where t is a Triangle?Print s2, which print() function will be called?Answer: Shape class’s print() will be caled.How about creating a Triangle t2=s? Will thiscompile?Create a (Triangle*)tptr to point to (&t)Create a (Shape*)sptr to point to (tptr)Call tptr->print()Call sptr->print()

*/

29

Copyright © William C. Cheng

30

Data Structures - CSCI 102

Copyright © William C. Cheng

inherit_main.cpp#include <iostream>#include <string>

#include "shape.h"#include "triangle.h"

using namespace std;

int main(){

//calls Shape class "print" functionShape s(100,100);s.print();

//calls Triangle class "print" functionTriangle t(20,40,5,10);t.print();

//Shape s2; //this will not compile

//calls Shape class "print" function (why?)Shape tri = t;tri.print();

//Triangle t2 = s; //this will not compile eitherTriangle *tptr=&t;Shape *sptr=tptr;sptr->print();

}

31

Data Structures - CSCI 102

Copyright © William C. Cheng

Under the Cover

...int main(){

...Triangle t(20,40,5,10);...

Triangle *tptr=&t;Shape *sptr=tptr;sptr->print();

}

Let’s focus on the end of inherit_main.cpp:

Put everything together and compile:

g++ -g -Wall inherit_main.cpp point.cpp

Run the debugger, set a breakpoint in main(), do a few nextcommands until you get to the last line

32

Data Structures - CSCI 102

Copyright © William C. Cheng

Under the Cover

gdb a.out(gdb) break main(gdb) run...(gdb) next(gdb) next(gdb) ...(gdb) next30 sptr->print();

Where is sptr->center stored?

33

Data Structures - CSCI 102

Copyright © William C. Cheng

Under the Cover

(gdb) print &sptr->center$3 = (Point *) 0xbff5a2e8

What are the values of tptr and sptr?(gdb) print tptr

$1 = (Triangle *) 0xbff5a2e8(gdb) print sptr

$2 = (Shape *) 0xbff5a2e8

They are pointing at the same memory location

Same place!

What about tptr->base and tptr->height?(gdb) print &tptr->base$4 = (int *) 0xbff5a2f0(gdb) print &tptr->height$5 = (int *) 0xbff5a2f4

Just below!

Data Structures - CSCI 102

Under the Cover0xbff5a2e8tptr

(gdb) print tptr$1 = (Triangle *) 0xbff5a2e8(gdb) print sptr$2 = (Shape *) 0xbff5a2e8(gdb) print &sptr->center$3 = (Point *) 0xbff5a2e8(gdb) print &tptr->base$4 = (int *) 0xbff5a2f0(gdb) print &tptr->height$5 = (int *) 0xbff5a2f4

34

Copyright © William C. Cheng

sptr

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x05

0x0a

0x14

0x28

center

baseheight

Data Structures - CSCI 102

Under the Cover0xbff5a2e8tptr

(gdb) print tptr$1 = (Triangle *) 0xbff5a2e8(gdb) print sptr$2 = (Shape *) 0xbff5a2e8(gdb) print &sptr->center$3 = (Point *) 0xbff5a2e8(gdb) print &tptr->base$4 = (int *) 0xbff5a2f0(gdb) print &tptr->height$5 = (int *) 0xbff5a2f4(gdb) print &sptr->center.x$6 = (int *) 0xbff5a2e8(gdb) print &sptr->center.y$7 = (int *) 0xbff5a2ec

35

Copyright © William C. Cheng

sptrcenter.x

center.ybase

height

0x00 0x00 0x00 0x05

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x0a

0x14

0x28

Data Structures - CSCI 102

Under the Cover0xbff5a2e8tptr

(gdb) print sizeof(*sptr)$8 = 8

36

Copyright © William C. Cheng

sptrcenter.x

center.ybase

height

0x00 0x00 0x00 0x05

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x0a

0x14

0x28

Data Structures - CSCI 102

Under the Cover0xbff5a2e8tptr

(gdb) print sizeof(*sptr)$8 = 8(gdb) print sizeof(*tptr)$9 = 16

37

Copyright © William C. Cheng

sptrcenter.x

center.ybase

height

0x00 0x00 0x00 0x05

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x00

0x0a

0x14

0x28