DOC PREVIEW
Yale CPSC 427 - Object-Oriented Programming
School name Yale University
Pages 23

This preview shows page 1-2-22-23 out of 23 pages.

Save
View full document
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
View full document
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience
Premium Document
Do you want full access? Go Premium and unlock all 23 pages.
Access to all documents
Download any document
Ad free experience

Unformatted text preview:

OutlineSTL and PolymorphismExceptionsOutline STL and Polymorphism ExceptionsCPSC 427a: Object-Oriented ProgrammingMichael J. FischerLecture 18November 9, 2010CPSC 427a 1/23Outline STL and Polymorphism ExceptionsSTL and PolymorphismExceptionsCPSC 427a 2/23Outline STL and Polymorphism ExceptionsSTL and PolymorphismCPSC 427a 3/23Outline STL and Polymorphism ExceptionsDerivation from STL containersCommon wisdom on the internet says not to inherit from STLcontainers.For example,http://en.wikipedia.org/wiki/Standard Template Library says,“STL containers are not intended to be used as baseclasses (their destructors are deliberately non-virtual);deriving from a container is a common mistake.”This reflects Rule 35 of Sutter and Alexandrescu,“Avoid inheriting from classes that were not designed tobe base classes.”CPSC 427a 4/23Outline STL and Polymorphism ExceptionsReplacing authority with understandingC++ is a complicated and powerful language.Some constructs such as classes are used for several differentpurposes.What is appropriate in one context may not be in another.Simple rules will not make you a good C++ programmer. Thought,understanding, and experience will.CPSC 427a 5/23Outline STL and Polymorphism ExceptionsTwo kinds of derivationC++ supports two distinct kinds of derivation:ISimple derivation.IPolymorphic derivation.class A { ... };class B : public A { ... };We say B is derived from A, and B inherits members from A.Each B object has an A object embedded within it.The derivation is simple if no members of A are virtual;otherwise it is polymorphic.CPSC 427a 6/23Outline STL and Polymorphism ExceptionsHow are they the same?With both kinds of derivation, a function of the base class A canbe overridden by a function in B.In both cases, one can create and delete objects of class B.Both A’s and B’s destructor are called when a B object is deleted.#include <iostream>class A { public:~A() { std::cout << "A’s destructor called" << std::endl; }};class B: public A { public:~B() { std::cout << "B’s destructor called" << std::endl; }};int main() { B bobj; }Output: B’s destructor calledA’s destructor calledCPSC 427a 7/23Outline STL and Polymorphism ExceptionsWhat is simple derivation good for?Some uses for simple derivation.ICode sharing. A common base can be extended in differentdirections through derivation.ICreating a new API to system resources (e.g., 12-StopWatchdemo).IIncreasing modularity through layering.With simple derivation, the derived class is the public interface.Often protected or private derivation is used to hide the baseclass from the users of the derived class.CPSC 427a 8/23Outline STL and Polymorphism ExceptionsWhat are the problems with simple derivation?ISeveral objects derived from the same base type have little incommon except for the embedded base type object in each.IA base type pointer can only access the embedded base typeobject. The rest of the derived object is present but invisible.This is called slicing, where the derived part is conceptually“sliced off”.CPSC 427a 9/23Outline STL and Polymorphism ExceptionsWhat is polymorphic derivation good for?IPolymorphic derivation allows for variability among objectswith a common interface.IThe base class (possibly pure abstract) defines the interface.IEach derived class defines a variant or implementation of theinterface.Some uses for polymorphic derivation.IHeterogeneous containers. Example: An array of differentkinds of employees.IA mechanism whereby old code can call new code. Byderiving from a predefined interface, existing functions thatcall virtual functions of the base class end up invoking newuser-provided code.CPSC 427a 10/23Outline STL and Polymorphism ExceptionsWhat are the problems of polymorphic derivation?Every polymorphic base class (containing even one virtualfunction) adds a runtime type tag to each instance.This costs in both time and space.ITime: Each call to a virtual function goes through a run-timedispatch table (the vtable).ISpace: Each instance of a polymorphic object contains a typetag, which takes extra space.IEvery polymorphic base class should have a virtualdestructor.CPSC 427a 11/23Outline STL and Polymorphism ExceptionsContrasts between simple and polymorphic derivationSimple derivation:ILow cost.IExtends the base class.IDerived class is the public interface; base class is a helper.ISlicing is generally avoided as being not useful.Polymorphic derivation:IHigher cost.IImplements the base class (in possibly multiple ways).IBase class is the public interface; derived classes are helpers.ISlicing is encouraged; virtual functions provide access tounderlying derived class objects.CPSC 427a 12/23Outline STL and Polymorphism ExceptionsContainment as an alternative to simple derivationOften the same class can be implemented using either containmentor derivation.Derivation:class A { ... f() ... };class B: public A { ... g() { f() ... } };A’s public member functions are inherited by B.Containment:class A { ... f() ... };class B { private: A a; ... g() { a.f() ... }public: f() { return a.f(); } };Access to A’s public member functions requires a “pass-through”function for delegation.CPSC 427a 13/23Outline STL and Polymorphism ExceptionsArgument for containmentContainment is a more distant relationship than derivation.Less coupling between classes is safer and less error-prone.Using containment, derived class is explicit about what is exported.For more info, see http://www.gotw.ca/publications/mill06.htm.CPSC 427a 14/23Outline STL and Polymorphism ExceptionsSTL container as a base classWe apply these concepts to STL base classes.Base classes are simple, not polymorphic (no virtual functions, novirtual destructor).This means that they should only be used with simple derivation.They are not suitable as base classes for polymorphic derivation.Often containment is preferable, but the large number of memberfunctions they support makes it cumbersome to get the samedegree of functionality in the derived class as comes “for free” withderivation.CPSC 427a 15/23Outline STL and Polymorphism ExceptionsCan I turn an STL container into a polymorphic base class?Yes, sort of. Here’s the idea.#include <iostream>#include <vector>using namespace std;class MyVectorInt : public vector<int> {public:MyVectorInt() : vector<int>() {}virtual ~MyVectorInt() {cout << "Base class destructor is called" << endl; }};class Derived : public MyVectorInt {public:~Derived() {cout << "Derived destructor is


View Full Document

Yale CPSC 427 - Object-Oriented Programming

Download Object-Oriented Programming
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Object-Oriented Programming and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Object-Oriented Programming 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?