Download presentation
Presentation is loading. Please wait.
Published bySharyl Stokes Modified over 9 years ago
1
Programming in C++ 1
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? 2
3
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” 4
5
#include 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
6
#include 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
7
Constructor A class constructor is a special member function of a class that is executed whenever we create new objects of that class. 7
8
#include 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
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. 9
10
#include 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
11
Overriding function Redefining a base class function in the derived class to have our own implementation is referred as overriding. 11
12
#include 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
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. 13
14
#include 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
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 15
16
Multiple Inheritance/Virtual Inheritance 16
17
Example of Exception 17 ExceptionDescription ArithmeticExceptionArithmetic error, such as divide-by-zero. ArrayIndexOutOfBoundsExceptionArray index is out-of-bounds. ArrayStoreExceptionAssignment to an array element of an incompatible type. ClassCastExceptionInvalid cast. IllegalArgumentExceptionIllegal argument used to invoke a method. IllegalMonitorStateExceptionIllegal monitor operation, such as waiting on an unlocked thread. IllegalStateExceptionEnvironment or application is in incorrect state. IllegalThreadStateExceptionRequested operation not compatible with current thread state. IndexOutOfBoundsExceptionSome type of index is out-of-bounds. NegativeArraySizeExceptionArray created with a negative size. NullPointerExceptionInvalid use of a null reference. NumberFormatExceptionInvalid conversion of a string to a numeric format. SecurityExceptionAttempt to violate security. StringIndexOutOfBoundsAttempt to index outside the bounds of a string. UnsupportedOperationExceptionAn unsupported operation was encountered.
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 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
19
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
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. 20
21
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
22 Exceptions Exception describes errors caused by your program and external circumstances. These errors can be caught and handled by your program.
23
23 Runtime Exceptions RuntimeException is caused by programming errors, such as bad casting, accessing an out-of-bounds array, and numeric errors.
24
24 Throwing Exceptions Example /** Set a new radius */ public void setRadius(double newRadius) throws IllegalArgumentException throws IllegalArgumentException { if (newRadius >= 0) radius = newRadius; else throw new IllegalArgumentException( "Radius cannot be negative"); }
25
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
26 Catching Exceptions
27
27 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Suppose no exceptions in the statements
28
28 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed
29
29 Trace a Program Execution animation try { statements; } catch(TheException ex) { handling ex; } finally { finalStatements; } Next statement; Next statement in the method is executed
30
30 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; Suppose an exception of type Exception1 is thrown in statement2
31
31 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The exception is handled.
32
32 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The final block is always executed.
33
33 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } finally { finalStatements; } Next statement; The next statement in the method is now executed.
34
34 Trace a Program Execution animation 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
35 Trace a Program Execution animation try { statement1; statement2; statement3; } catch(Exception1 ex) { handling ex; } catch(Exception2 ex) { handling ex; throw ex; } finally { finalStatements; } Next statement; Handling exception
36
36 Trace a Program Execution animation 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
37 Trace a Program Execution animation 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
38
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.