Download presentation
Presentation is loading. Please wait.
Published byἹερώνυμος Βονόρτας Modified over 6 years ago
1
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
2
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
3
Example: Divide By Zero
Write a function to calculate x/y If y is 0, throw an exception
4
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
5
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 }
6
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
7
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()
8
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
9
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
10
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
11
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
12
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
13
Subclass AcCess
14
Subclass Access
15
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
16
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)
17
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
18
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
19
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
20
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
21
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”
22
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
23
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!
24
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;
25
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
26
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
27
Standard Library A set of packaged generics that come with standard C++ Examples Doubly linked lists Queues Stacks Maps Multi-threading … Full list:
28
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
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.