30
Advanced C++ Advanced C++ Topics Topics Chapter 8 Chapter 8

Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

Embed Size (px)

Citation preview

Page 1: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

Advanced C++ TopicsAdvanced C++ Topics

Chapter 8Chapter 8

Page 2: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 2Chapter 8 -- Advanced C++ Topics

This chapter describes techniques that make This chapter describes techniques that make collections of reusable software components collections of reusable software components possible.possible. InheritanceInheritance Virtual Functions and Late BindingsVirtual Functions and Late Bindings FriendsFriends Class TemplatesClass Templates Overloaded OperatorsOverloaded Operators IteratorsIterators

Page 3: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 3Chapter 8 -- Advanced C++ Topics

Inheritance RevisitedInheritance Revisited

Inheritance is a relationship among classes.Inheritance is a relationship among classes. One class can derive the behavior and structure of One class can derive the behavior and structure of

another class.another class. On the next page we see relationships among On the next page we see relationships among

timepiecestimepieces

Page 4: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 4Chapter 8 -- Advanced C++ Topics

A digital alarm clock is a digital clockA digital alarm clock is a digital clock

Page 5: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 5Chapter 8 -- Advanced C++ Topics

Def: derived class (subclass)Def: derived class (subclass) Def: base class (superclass)Def: base class (superclass)

In C++, a derived class inherits all the members of In C++, a derived class inherits all the members of its base class, excepts the constructors and its base class, excepts the constructors and destructor.destructor.

Some languages allow you to have more than 1 Some languages allow you to have more than 1 base class.base class.

Page 6: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 6Chapter 8 -- Advanced C++ Topics

Inheritance allows you to reuse software Inheritance allows you to reuse software components when you define a new class.components when you define a new class.

Page 7: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 7Chapter 8 -- Advanced C++ Topics

Class Sphere{Class Sphere{

public:public:

Sphere();Sphere();

Sphere(double initialRadius);Sphere(double initialRadius);

void SetRadius(double newRadius);void SetRadius(double newRadius);

double getRadius() const;double getRadius() const;

double getDiameter() cosnt;double getDiameter() cosnt;

double getCircumference();double getCircumference();

double getArea() const;double getArea() const;

double getVolume() const;double getVolume() const;

double displayStatistics() const;double displayStatistics() const;

private:private:

double theRadius;double theRadius;

};};

Page 8: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 8Chapter 8 -- Advanced C++ Topics

Class Ball: public SphereClass Ball: public Sphere

{{

public:public:

Ball();Ball();

Ball(double initialRadius, cosnt string initialName);Ball(double initialRadius, cosnt string initialName);

void getName(string currentName) const;void getName(string currentName) const;

void setName(const string newName);void setName(const string newName);

void resetBall(double newRadius, const string newName);void resetBall(double newRadius, const string newName);

double displayStatistics() const;double displayStatistics() const;

private:private:

string theName;string theName;

};};

Page 9: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 9Chapter 8 -- Advanced C++ Topics

Ball::Ball() : Sphere()Ball::Ball() : Sphere()

{ setName(“”); }{ setName(“”); }

Ball::Ball(double initialRadius, const string initialName): Ball::Ball(double initialRadius, const string initialName): Sphere(initialRadius)Sphere(initialRadius)

{ setName(initialName);}{ setName(initialName);}

void Ball::resetBall(double newRadius, const string newName)void Ball::resetBall(double newRadius, const string newName)

{{

setRadius(newRadius);setRadius(newRadius);

setName(newName);setName(newName);

}}

void Ball::displayStatistics() constvoid Ball::displayStatistics() const

{ cout << “statistics for a “<< theName << “:”;{ cout << “statistics for a “<< theName << “:”;

Sphere::displayStatistics(); }Sphere::displayStatistics(); }

Page 10: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 10Chapter 8 -- Advanced C++ Topics

Ball myBall(5.0, “Volleyball”);Ball myBall(5.0, “Volleyball”); Sphere myShpere();Sphere myShpere();

The compiler can tell which function to use at compile time The compiler can tell which function to use at compile time and this is called early binding or static bindingand this is called early binding or static binding

Page 11: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 11Chapter 8 -- Advanced C++ Topics

A derived class’s constructor executes after the A derived class’s constructor executes after the base class’s constructor.base class’s constructor. Built inside outBuilt inside out

The destructor of the derived class executes The destructor of the derived class executes before the destructor of the base class.before the destructor of the base class. Destroyed outside inDestroyed outside in

Page 12: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 12Chapter 8 -- Advanced C++ Topics

Addition of the protected sectionAddition of the protected section

Page 13: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 13Chapter 8 -- Advanced C++ Topics

Public, Private, and Protected InheritancePublic, Private, and Protected Inheritance Several kinds of inheritance are possible.Several kinds of inheritance are possible.

The key is -- if you have layers of inheritance, how are The key is -- if you have layers of inheritance, how are the lower layers treated.the lower layers treated.

Public inheritance Public inheritance Public and protected members of the base class remain public Public and protected members of the base class remain public

and protected members of the derived classand protected members of the derived class

Protected inheritanceProtected inheritance Public and protected members of the base class are protected Public and protected members of the base class are protected

members of the derived classmembers of the derived class

Private inheritancePrivate inheritance Public and protected members of the base class are private Public and protected members of the base class are private

members of the derived class.members of the derived class.

Page 14: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 14Chapter 8 -- Advanced C++ Topics

Is-a, Has-a, and As-a RelationshipsIs-a, Has-a, and As-a Relationships Is-a relationships - public inheritanceIs-a relationships - public inheritance

A Ball is a Sphere A Ball is a Sphere Whatever is true of type sphere is also true of type ballWhatever is true of type sphere is also true of type ball

This is called This is called object type compatibilityobject type compatibility

void displayDiameter(Sphere thing)void displayDiameter(Sphere thing) {{ cout << “The diameter is “cout << “The diameter is “ << thing.getDiameter() << “.\n”;<< thing.getDiameter() << “.\n”; }}

Page 15: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 15Chapter 8 -- Advanced C++ Topics

If you define mySphere and myBall asIf you define mySphere and myBall as Sphere mySphere(2.0);Sphere mySphere(2.0); Ball myBall(5.0, “Volleyball”);Ball myBall(5.0, “Volleyball”);

The following calls are legal:The following calls are legal: displayDiameter(mySphere);displayDiameter(mySphere); displayDiameter(myBall);displayDiameter(myBall);

Page 16: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 16Chapter 8 -- Advanced C++ Topics

Has-a relationshipHas-a relationship A ball point pen has a ballA ball point pen has a ball

class Penclass Pen {{ ...... Private:Private: Ball point;Ball point; };};

Thus another name for the has-a relationship is Thus another name for the has-a relationship is containment.containment.

Page 17: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 17Chapter 8 -- Advanced C++ Topics

As-a relationshipAs-a relationship You can implement a Stack as a listYou can implement a Stack as a list

class Stack: private Listclass Stack: private List

Thus within the Stack you can manipulate the list by Thus within the Stack you can manipulate the list by using list’s methods.using list’s methods.

Both descendants and clients of stack, however, would Both descendants and clients of stack, however, would not be able to access any members of List.not be able to access any members of List.

Page 18: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 18Chapter 8 -- Advanced C++ Topics

Virtual Functions and Late BindingVirtual Functions and Late Binding

Example:Example: Case 1:Case 1:

Sphere *spherePtr = &mySphereSphere *spherePtr = &mySphere spherePtr->displayStatistics();spherePtr->displayStatistics();

Case 2:Case 2: spherePtr = &myBall;spherePtr = &myBall; spherePtr->displayStatistics();spherePtr->displayStatistics();

What is the difference, what functions get called?What is the difference, what functions get called?

Page 19: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 19Chapter 8 -- Advanced C++ Topics

Answer: They both invoke sphere’s version of Answer: They both invoke sphere’s version of displayStatistics()displayStatistics() because of early binding. because of early binding.

We need to tell the compiler that the function We need to tell the compiler that the function might be changed so it will not bind at compile might be changed so it will not bind at compile time but will wait until run-time to see which one time but will wait until run-time to see which one to call.to call.

You do this with the keyword You do this with the keyword virtualvirtual

Page 20: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 20Chapter 8 -- Advanced C++ Topics

In the base class you do it this wayIn the base class you do it this way

class Sphere{class Sphere{ public:public: ...... virtual void displayStatistics() const;virtual void displayStatistics() const; ...... };};

Now the compiler will do late binding or dynamic Now the compiler will do late binding or dynamic binding.binding.

Page 21: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 21Chapter 8 -- Advanced C++ Topics

displayStatisticsdisplayStatistics is called a is called a polymorphicpolymorphic function function polymorphism means many forms.polymorphism means many forms.

We also say that Balls’ version of We also say that Balls’ version of displayStatisticsdisplayStatistics overrides Sphere’s version overrides Sphere’s version

Now let’s look at some examples of how early and Now let’s look at some examples of how early and late binding can interact.late binding can interact.

Page 22: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 22Chapter 8 -- Advanced C++ Topics

Assume display statistics is virtual and getArea is Assume display statistics is virtual and getArea is not.not.

Now if it is ....Now if it is ....

Page 23: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 23Chapter 8 -- Advanced C++ Topics

Page 24: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 24Chapter 8 -- Advanced C++ Topics

Page 25: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 25Chapter 8 -- Advanced C++ Topics

Abstract Base ClassesAbstract Base Classes If your base class has a virtual function that all of If your base class has a virtual function that all of

its descendants will have to overload, its descendants will have to overload, you can give just a prototype and no code you can give just a prototype and no code This is called a pure virtual function This is called a pure virtual function

virtual void setRadius(double newRadius) = 0;virtual void setRadius(double newRadius) = 0;

Any class with pure virtual functions (or a derived class Any class with pure virtual functions (or a derived class that has not defined all pure virtual functions) is called that has not defined all pure virtual functions) is called an Abstract Base class, and no instances of it can be an Abstract Base class, and no instances of it can be declared.declared.

Page 26: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 26Chapter 8 -- Advanced C++ Topics

FriendsFriends

Declaring a non-member function as a friend Declaring a non-member function as a friend to a class allows that function to access all the to a class allows that function to access all the private members of the classprivate members of the class For example: input and output functions are often For example: input and output functions are often

defined as friend functionsdefined as friend functions

You also saw class fiends in your linked list nodes.You also saw class fiends in your linked list nodes.

Page 27: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 27Chapter 8 -- Advanced C++ Topics

Class TemplatesClass Templates

You can avoid multiple class definitions by You can avoid multiple class definitions by using a C++ class template to specify a class in using a C++ class template to specify a class in terms of a data-type parameter.terms of a data-type parameter.

You have used templates since the middle of You have used templates since the middle of CS 202CS 202

Page 28: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 28Chapter 8 -- Advanced C++ Topics

Overloaded OperatorsOverloaded Operators

An operator with more than one meaning is An operator with more than one meaning is said to be overloaded and is an example of a said to be overloaded and is an example of a simple form of polymorphismsimple form of polymorphism

To overload an operator, you define an To overload an operator, you define an operator function whose name has the formoperator function whose name has the form operator operator symbolsymbol

where where symbolsymbol is the operator that you want to is the operator that you want to overloadoverload

Page 29: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 29Chapter 8 -- Advanced C++ Topics

IteratorsIterators

An iterator traverses a collection of objectsAn iterator traverses a collection of objects Typically an iterator has an operation that Typically an iterator has an operation that

accesses the item it currently references.accesses the item it currently references. Usually this is implemented by overloading the Usually this is implemented by overloading the

dereference operator, *dereference operator, * Iterators also have operations that move the Iterators also have operations that move the

iterator forward and backward through a iterator forward and backward through a collection (++, --). They also usually have == collection (++, --). They also usually have == and != overloaded as well.and != overloaded as well.

Page 30: Advanced C++ Topics Chapter 8. CS 308 2Chapter 8 -- Advanced C++ Topics This chapter describes techniques that make collections of reusable software components

CS 308 30Chapter 8 -- Advanced C++ Topics