1 / 38

Chapter 6 inheritence

Programming in C++. Chapter 6 inheritence. 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

mick
Télécharger la présentation

Chapter 6 inheritence

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Programming in C++ Chapter 6 inheritence

  2. 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?

  3. Overview Inheritance is a way to establish  relationships between objects

  4. 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”

  5. #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 • intGetAge() const { return itsAge; } • void SetAge(int age) { itsAge = age; } • intGetWeight() 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: • intitsAge; • intitsWeight; • }; • 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; • }

  6. #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(); • }

  7. Constructor • A class constructor is a special member function of a class that is executed whenever we create new objects of that class.

  8. #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; • }

  9. 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.

  10. #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; • }

  11. Overriding function • Redefining a base class function in the derived class to have our own implementation is referred as overriding.

  12. #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();}

  13. 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.

  14. #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; }

  15. 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

  16. Multiple Inheritance/Virtual Inheritance

  17. Example of Exception

  18. 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 • 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

  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 • 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

  20. Friendly Advice about Exception • Actually, it is very difficult to remember all exception especially to junior programmer. However, the programmer can use online recourses.

  21. System Errors 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 Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.

  23. Runtime Exceptions 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 Exceptions try { 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

  27. animation Trace a Program Execution Suppose no exceptions in the statements try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement;

  28. animation Trace a Program Execution The final block is always executed try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement;

  29. animation Trace a Program Execution Next statement in the method is executed try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement;

  30. animation Trace a Program Execution Suppose an exception of type Exception1 is thrown in statement2 try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;

  31. animation Trace a Program Execution The exception is handled. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;

  32. animation Trace a Program Execution The final block is always executed. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;

  33. animation Trace a Program Execution The next statement in the method is now executed. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement;

  34. animation Trace a Program Execution statement2 throws an exception of type Exception2. try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;

  35. animation Trace a Program Execution Handling exception try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;

  36. animation Trace a Program Execution Execute the final block try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;

  37. animation Trace a Program Execution Rethrow the exception and control is transferred to the caller try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement;

  38. Exercise • Develop a C++ program that can save 10 book information (string) & display 10 book information (string), andalso the program will give WARNING if user try to key in integer (this part you should use exception handling). • InputMismatchException

More Related