Programming in C++ 1. Learning Outcome At the end of this slide, student able to: Understand what...
-
Upload
sharyl-stokes -
Category
Documents
-
view
216 -
download
1
Transcript of Programming in C++ 1. Learning Outcome At the end of this slide, student able to: Understand what...
CHAPTER 6 INHERITENCE
Programming in C++
1
Learning Outcome
At the end of this slide, student able to:
Understand what is Inheritance? Compare between inheritance and derivation Distinguish between constructors and destructors Understand the overriding function Understand the virtual methods
Examine the implementation of the concept of polymorphism. Examine the problems with single inheritance Define multiple and virtual inheritance. What are the limitations of abstract data types?
2
3
Overview
Inheritance is a way to establish relationships between objects
Derivation
Derivation is the definition of a new class by extending one or more existing classes.
Create new class Dog that derive from Mammal.
“class Dog : public Mammal”
4
#include <iostream> using std::cout; using std::endl; enum BREED { GOLDEN, CAIRN, DANDIE, SHETLAND, DOBERMAN, LAB }; class Mammal { public: // constructors Mammal():itsAge(2), itsWeight(5){} ~Mammal(){} //accessors int GetAge() const { return itsAge; } void SetAge(int age) { itsAge = age; } int GetWeight() const { return itsWeight; } void SetWeight(int weight) { itsWeight = weight; } //Other methods void Speak()const { cout << " Mammal sound!\n" ; } void Sleep()const { cout << " shhh. I’m sleeping.\n" ; } protected: int itsAge; int itsWeight; }; class Dog : public Mammal { public: // Constructors Dog():itsBreed(GOLDEN){} ~Dog(){} // Accessors BREED GetBreed() const { return itsBreed; } void SetBreed(BREED breed) { itsBreed = breed; }
// Other methods void WagTail() const { cout << " Tail wagging...\n" ; } void BegForFood() const { cout << " Begging for food...\n" ; } private: BREED itsBreed; }; int main() { Dog Fido; Fido.Speak(); Fido.WagTail(); cout << "Fido is " << Fido.GetAge() << " years old" << endl; return 0; }
5
#include <iostream> using namespace std;
class Base { public: char* name; void display() { cout << name << endl; } };
class Derived: public Base { public: char* name; void display() { cout << name << ", " << Base::name << endl; } };
int main() { Derived d; d.name = "Derived Class"; d.Base::name = "Base Class";
// call Derived::display() d.display();
// call Base::display() d.Base::display(); }
6
Constructor
A class constructor is a special member function of a class that is executed whenever we create new objects of that class.
7
#include <iostream> using namespace std; class Line { public: void setLength( double len ); double getLength( void ); Line(); // This is the constructor private: double length; }; // Member functions definitions including constructor Line::Line(void) { cout << "Object is being created" << endl; } void Line::setLength( double len ) { length = len; } double Line::getLength( void ) { return length; } // Main function for the program int main( ) { Line line; // set line length line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; return 0; }
8
Destructor
A destructor is a special member function of a class that is executed whenever an object of it's class goes out of scope or whenever the delete expression is applied to a pointer to the object of that class.
9
#include <iostream> using namespace std; class Line { public: void setLength( double len ); double getLength( void ); Line(); // This is the constructor declaration ~Line(); // This is the destructor: declaration private: double length; }; // Member functions definitions including constructor Line::Line(void) { cout << "Object is being created" << endl; } Line::~Line(void) { cout << "Object is being deleted" << endl; } void Line::setLength( double len ) { length = len; } double Line::getLength( void ) { return length; } // Main function for the program int main( ) { Line line; // set line length line.setLength(6.0); cout << "Length of line : " << line.getLength() <<endl; line.setLength(9.0); cout << "Length of line : " << line.getLength() <<endl; return 0; }
10
Overriding function
Redefining a base class function in the derived class to have our own implementation is referred as overriding.
11
#include <iostream>using namespace std;
class Base {public:virtual void myfunc() {cout << "Base::myfunc .." << endl;}};
class Derived : public Base {public:void myfunc() {cout << "Derived::myfunc .." << endl;}};
void main(){Derived d;d.myfunc();}
12
Virtual Function
A virtual function is a special type of function that resolves to the most-derived version of the function with the same signature.
To make a function virtual, simply place the “virtual” keyword before the function declaration.
13
#include <iostream> using namespace std;
class B { public: virtual void display() /* Virtual function */ { cout<<"Content of base class.\n"; } };
class D1 : public B { public: void display() { cout<<"Content of first derived class.\n"; } };
class D2 : public B { public: void display() { cout<<"Content of second derived class.\n"; } };
int main() { B *b; D1 d1; D2 d2; /* b->display(); // You cannot use this code here because the function of base class is virtual. */ b = &d1; b->display(); /* calls display() of class derived D1 */ b = &d2; b->display(); /* calls display() of class derived D2 */ return 0; }
14
Polymorphism
C++ polymorphism means that a call to a member function will cause a different function to be executed depending on the type of object that invokes the function.
That means, polymorphism can be described as CALLING TECHNIQUE
15
Multiple Inheritance/Virtual Inheritance
16
Example of Exception
17
Exception Description
ArithmeticException Arithmetic error, such as divide-by-zero.
ArrayIndexOutOfBoundsException Array index is out-of-bounds.
ArrayStoreException Assignment to an array element of an incompatible type.
ClassCastException Invalid cast.
IllegalArgumentException Illegal argument used to invoke a method.
IllegalMonitorStateException Illegal monitor operation, such as waiting on an unlocked thread.
IllegalStateException Environment or application is in incorrect state.
IllegalThreadStateException Requested operation not compatible with current thread state.
IndexOutOfBoundsException Some type of index is out-of-bounds.
NegativeArraySizeException Array created with a negative size.
NullPointerException Invalid use of a null reference.
NumberFormatException Invalid conversion of a string to a numeric format.
SecurityException Attempt to violate security.
StringIndexOutOfBounds Attempt to index outside the bounds of a string.
UnsupportedOperationException An unsupported operation was encountered.
Other Exception AWTException AclNotFoundException ActivationException AlreadyBoundException ApplicationException ArithmeticException ArrayIndexOutOfBoundsException AssertionException BackingStoreException BadAttributeValueExpException BadBinaryOpValueExpException BadLocationException BadStringOperationException BatchUpdateException BrokenBarrierException CertificateException ChangedCharSetException CharConversionException CharacterCodingException ClassCastException ClassNotFoundException CloneNotSupportedException ClosedChannelException ConcurrentModificationException DataFormatException
18
• DatatypeConfigurationException• DestroyFailedException• EOFException• Exception• ExecutionException• ExpandVetoException• FileLockInterruptionException• FileNotFoundException• FishFaceException• FontFormatException• GSSException• GeneralSecurityException• IIOException• IOException• IllegalAccessException• IllegalArgumentException• IllegalClassFormatException• IllegalStateException• IndexOutOfBoundsException • InputMismatchException• InstantiationException• InterruptedException• InterruptedIOException• IntrospectionException• InvalidApplicationException• InvalidMidiDataException• InvalidPreferencesFormatException• InvalidTargetObjectTypeException
InvocationTargetException JAXBException JMException KeySelectorException LastOwnerException LineUnavailableException MalformedURLException MarshalException MidiUnavailableException MimeTypeParseException NamingException NegativeArraySizeException NoSuchElementException NoSuchFieldException NoSuchMethodException NoninvertibleTransformException NotBoundException NotOwnerException NullPointerException NumberFormatException ObjectStreamException ParseException ParserConfigurationException PrintException PrinterException PrivilegedActionException PropertyVetoException
19
• ProtocolException• RefreshFailedException• RemarshalException• RemoteException• RuntimeException• SAXException• SOAPException• SQLException• SQLWarning• SSLException• ScriptException• ServerNotActiveException• SocketException• SyncFailedException• TimeoutException• TooManyListenersException• TransformException• TransformerException• URIReferenceException• URISyntaxException• UTFDataFormatException• UnknownHostException• UnknownServiceException• UnmodifiableClassException• UnsupportedAudioFileException• UnsupportedCallbackException• UnsupportedEncodingException• UnsupportedFlavorException• UnsupportedLookAndFeelException• UnsupportedOperationException• UserException• XAException• XMLParseException• XMLSignatureException• XMLStreamException• XPathException• ZipException
Friendly Advice about Exception
Actually, it is very difficult to remember all exception especially to junior programmer. However, the programmer can use online recourses.
20
21
System Errors
LinkageError
Error
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Many more classes
Many more classes
Many more classes
IllegalArgumentException
System errors are thrown by JVM and represented in the Error class. The Error class describes internal system errors. Such errors rarely occur. If one does, there is little you can do beyond notifying the user and trying to terminate the program gracefully.
22
Exceptions
LinkageError
Error
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Many more classes
Many more classes
Many more classes
IllegalArgumentException
Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
23
Runtime Exceptions
LinkageError
Error
Throwable
ClassNotFoundException
VirtualMachineError
IOException
Exception
RuntimeException
Object
ArithmeticException
NullPointerException
IndexOutOfBoundsException
Many more classes
Many more classes
Many more classes
IllegalArgumentException
RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
24
Throwing Exceptions Example
/** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
25
Catching Exceptionstry { statements; // Statements that may throw exceptions}catch (Exception1 exVar1) { handler for exception1;}catch (Exception2 exVar2) { handler for exception2;}...catch (ExceptionN exVar3) { handler for exceptionN;}
26
Catching Exceptions
main method { ... try { ... invoke method1; statement1; } catch (Exception1 ex1) { Process ex1; } statement2; }
method1 { ... try { ... invoke method2; statement3; } catch (Exception2 ex2) { Process ex2; } statement4; }
method2 { ... try { ... invoke method3; statement5; } catch (Exception3 ex3) { Process ex3; } statement6; }
An exception is thrown in method3
Call Stack
main method main method
method1
main method
method1
main method
method1
method2 method2
method3
27
Trace a Program Executionanimation
try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }
Next statement;
Suppose no exceptions in the statements
28
Trace a Program Executionanimation
try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }
Next statement;
The final block is always executed
29
Trace a Program Executionanimation
try { statements;}catch(TheException ex) { handling ex; }finally { finalStatements; }
Next statement;
Next statement in the method is executed
30
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }
Next statement;
Suppose an exception of type Exception1 is thrown in statement2
31
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }
Next statement;
The exception is handled.
32
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }
Next statement;
The final block is always executed.
33
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }finally { finalStatements; }
Next statement;
The next statement in the method is now executed.
34
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }
Next statement;
statement2 throws an exception of type Exception2.
35
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }
Next statement;
Handling exception
36
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }
Next statement;
Execute the final block
37
Trace a Program Executionanimation
try { statement1; statement2; statement3;}catch(Exception1 ex) { handling ex; }catch(Exception2 ex) { handling ex; throw ex;}finally { finalStatements; }
Next statement;
Rethrow the exception and control is transferred to the caller
Exercise
Develop a C++ program that can save 10 book information (string) & display 10 book information (string), and also the program will give WARNING if user try to key in integer (this part you should use exception handling).
InputMismatchException
38