Exceptions An exception signals an error, and has the ability to propagate upward through the call stack for easier management To “raise” an exception,

Slides:



Advertisements
Similar presentations
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Advertisements

Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Road Map Introduction to object oriented programming. Classes
Chapter 10 Classes Continued
8.1 Classes & Inheritance Inheritance Objects are created to model ‘things’ Sometimes, ‘things’ may be different, but still have many attributes.
OOP Languages: Java vs C++
Programming Languages and Paradigms Object-Oriented Programming.
Chapter 12: Adding Functionality to Your Classes.
C++ Object Oriented 1. Class and Object The main purpose of C++ programming is to add object orientation to the C programming language and classes are.
Polymorphism &Virtual Functions
Lecture 8 Inheritance Richard Gesick. 2 OBJECTIVES How inheritance promotes software reusability. The concepts of base classes and derived classes. To.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
Introduction to Object Oriented Programming. Object Oriented Programming Technique used to develop programs revolving around the real world entities In.
Object Orientation Yaodong Bi, Ph.D. Department of Computer Sciences University of Scranton October 18, 2015October 18, 2015October 18, 2015.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Data Structures Using Java1 Chapter 2 Inheritance and Exception Handling.
Copyright 2006 Oxford Consulting, Ltd1 February Polymorphism Polymorphism Polymorphism is a major strength of an object centered paradigm Same.
Copyright © 2012 Pearson Education, Inc. Chapter 15: Inheritance, Polymorphism, and Virtual Functions.
Programming with Java © 2002 The McGraw-Hill Companies, Inc. All rights reserved. 1 McGraw-Hill/Irwin Chapter 5 Creating Classes.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
CS-1030 Dr. Mark L. Hornick 1 Basic C++ State the difference between a function/class declaration and a function/class definition. Explain the purpose.
Chapter -6 Polymorphism
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
Overview of C++ Polymorphism
Object orientation and Packaging in Java Object Orientation and Packaging Introduction: After completing this chapter, you will be able to identify.
Recap Introduction to Inheritance Inheritance in C++ IS-A Relationship Polymorphism in Inheritance Classes in Inheritance Visibility Rules Constructor.
COP INTERMEDIATE JAVA Inheritance, Polymorphism, Interfaces.
COMPUTER SCIENCE & TECHNOLOGY DEGREE PROGRAMME FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UVA WELLASSA ‏ Properties of Object Oriented Programming.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Java Programming: Guided Learning with Early Objects Chapter 9 Inheritance and Polymorphism.
Chapter 2 Objects and Classes
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Modern Programming Tools And Techniques-I
Inheritance Chapter 7 Inheritance Basics Programming with Inheritance
Andy Wang Object Oriented Programming in C++ COP 3330
Inheritance and Polymorphism
Object-Oriented Programming
Chapter 5 Classes.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
The dirty secrets of objects
Inheritance Often, software encapsulates multiple concepts for which some attributes/behaviors overlap E.g. A computer (role-playing) game has: Monsters:
Object Orientation Yaodong Bi, Ph.D. Department of Computer Sciences
Understanding Inheritance
CSC 143 Inheritance.
Chapter 9 Inheritance and Polymorphism
Exception Handling Chapter 9.
Inheritance Basics Programming with Inheritance
Learning Objectives Inheritance Virtual Function.
Java Programming Language
Lecture 22 Inheritance Richard Gesick.
Virtual Functions Department of CSE, BUET Chapter 10.
Inheritance Dr. Bhargavi Goswami Department of Computer Science
Inheritance, Polymorphism, and Virtual Functions
Polymorphism Polymorphism
Computer Programming with JAVA
Java – Inheritance.
9: POLYMORPHISM Programming Technique II (SCSJ1023) Jumail Bin Taliba
Polymorphism Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.
Java Inheritance.
CISC/CMPE320 - Prof. McLeod
Fundaments of Game Design
Overview of C++ Polymorphism
VIRTUAL FUNCTIONS RITIKA SHARMA.
Final and Abstract Classes
Lecture 10 Concepts of Programming Languages
C++ Object Oriented 1.
Computer Science II for Majors
Presentation transcript:

Exceptions An exception signals an error, and has the ability to propagate upward through the call stack for easier management To “raise” an exception, syntax: throw “Error message here.\n”; The argument to “throw” can be any type object – e.g. to hold more data about the current context of the exception

Exceptions To catch an exception, enclose the volatile code in a try{ … } block Then the optional following catch (ExceptionType e) { … } block gets triggered when the type of the exception matches ExceptionType, and the argument to “throw” gets stored in “e”. The catch block is then executed and the code continues after the entire try…catch sequence Uncaught exceptions typically cause programs to halt, but can depend on their execution environment

Example: Divide By Zero Write a function to calculate x/y If y is 0, throw an exception

Example: Overloaded [] operator For a list, overload the [] operator, but throw an exception when the passed index is out of bounds Prototype: ReturnType& ClassName::operator[](IndexType b); Useful for lists, but have to handle out-of-bounds via exceptions or other error handling Can overload for specific object parameters, for more semantic indexing

Advanced Class Features Static vs instance members Static: bound to the class itself as a globally accessible variable Instance: bound to individual objects of the class E.g. class Student{ static int studentCount; //shared across all instances std::string name; // Specific to single instances }

Static Member variables Declared with “static” modifier before type Must be initialized outside the class (unless also a const) E.g. int Student::studentCount = 0; Shared across all class members Can also be accessed by ClassName::varName if it is public

Static member functions Declared with “static” before the return type Cannot access any instance variables Does not need a class to be instantiated to call: MyClass::someStaticFunc() Can also be called from a class object: instanceObj.someStaticFunc()

Friends of Classes We can specify that functions (or entire classes) are allowed to access private members of a certain class Syntax: friend ReturnType FunctionName (ParameterTypeList) Can also declare entire classes a friend, but isn’t generally useful, since it allows access to any member functions of the friend, even ones added later Better off just combining the classes

Inheritance Often, software encapsulates multiple concepts for which some attributes/behaviors overlap E.g. A computer (role-playing) game has: Monsters: name, location, hp, equipment, faction, AI details, etc. Players: name, location, hp, equipment, customization, input handling, etc. Objects: name, location, type, effects, price, etc. C++ provides semantics to help prevent duplication of functionality (not through templates), and allowing classes to be related to each other

Subclasses Syntax: class ParentClass{ … }; class ChildClass : ParentClass { … } We call ParentClass the “Base Class” and ChildClass the “Derived Class” In a derived class, it inherits all members of the base class! Methods Attributes However, access may be limited

Class Access Private members of a base class are inaccessible to the derived classes, unless through accessible mutators/accessors What about public? We can control their behavior! New access specifier: “protected” Same as private, but will change subclass behavior

Subclass Access The access specification (public, protected, private) determines how the base class members are inherited class ChildClass : public ParentClass { … } class ChildClass : protected ParentClass { … } class ChildClass : private ParentClass { … } class ChildClass : ParentClass { … } // Defaults to private

Subclass AcCess

Subclass Access

Subclass Access Summary: Base class private members are never (directly) accessible from derived But they’re still there! “private” makes public and protected base members private in the derived class “protected” makes public and protected base members protected in the derived class “public” keeps public and protected base members the same access in the derived class

Subclass creation/deletion What needs to happen when we have B : A and then call “new B()” ? Since B has all the same attributes as A, it makes sense that they need to be initialized the same way for a regular A object The base class constructor is called first, then the derived class constructor When destructing, they are called in reverse order (derived first, then base)

Non-Default Constructors If we need to pass arguments to the base constructor, we can! Consider classes Rectangle, and Cube : Rectangle Suppose rectangle holds the length and width of a rectangle Cube adds a height member Rectangle has non-default ctor: Rectangle(int len, int wid) If we want the non-default ctor for cube, we can define: Cube(int l, int w, int h) : Rectangle(w, l) { height = h; } Calls Rectangle(w, l) first, then sets the height

Constructor Summary General format: ClassName::ClassName(ParameterList) : BaseClassName(ArgumentList) But by default, the base default constructor will be called first, so we can omit the second half if we’re ok with that

Redefining Inherited Members Main idea: we can re-define (aka override) inherited member functions or variables Be careful of naming conflicts, they do not throw errors! Example: override “Person” name getter to add title

Class Hierarchy One can chain inheritence Parlance: A B D C If A is a class, and B : A We can also write C : B C would inherit from B as normal We can also add D : A Parlance: “B is a A” “C is a B” ”D is a A” A B D C

Polymorphism Main idea: a reference/pointer to a particular object can also serve as a reference/pointer to any superclass of that object E.g. If we have class “Person” and “Faculty : Person” we can do Person* p = new Faculty( … ); // Different types, but is valid! E.g. If we have class “Person” and “Faculty : Person” We can define function print(Person& p), then call it with a “Faculty” argument! But, as written, will not call overloaded members inside “Faculty”

Polymorphism Dynamic Binding: Determining which functions to call at runtime, versus at compile time In the polymorphic example above, any private members of the ”Person& p” parameter are bound at compile time I.e. if we overloaded any, they would be ignored :( We can enable dynamic binding by using the virtual keyword in the prototype: virtual returnType functionName( parameterList ); The compiler will then not bind and wait until runtime The virtual keyword is inherited by any overrides

Polymorphism In general, any potential super class should have a virtual destructor Using the example above: Person* p = new Faculty(); // Calls both constructors delete p; // Only calls the Person destructor!

Inheritance Pitfalls Overriding a member that you should not E.g. id number attributes Prevent with final modifier at the end of the prototype, e.g., virtual returnType funcName(params) const final; Failing to override a function because (slightly) different signature Class Person{ functionA() const; } Class Faculty : Person { functionA(); } Bad bad bad! Does not override! The compiler can help: keyword override tells it that it should be overriding a base class member, e.g., virtual returnType funcName(params) const override;

Abstract Base Class An “Abstract” class is a class which contains a pure virtual function Pure virtual function has the virtual keyword and is prototyped with “= 0”, e.g., virtual int getNumber() const = 0; // pure virtual Abstract classes cannot be directly instantiated, and any non-virtual subclasses must override all pure virtual functions

Multiple Inheritance With similar syntax, a class can inherit from multiple base classes To justify this, return to the “building blocks” analogy of inheritance Can be difficult because of ambiguous member definitions More information in the book Not covered in detail in this course

Standard Library A set of packaged generics that come with standard C++ Examples Doubly linked lists Queues Stacks Maps Multi-threading … Full list: http://en.cppreference.com/w/cpp/header

Example: Polymorphism In Games Write a text-based adventure that lets the user choose different options, changing the “state” of the game with each option Main Idea: The state will be an instance of a polymorphic class, where state- specific actions override some super-class We will employ some standard library tools