CS Week 8 - Inheritance and Polymorphism Flashcards
Derived class
a class that is derived from another class (base class or superclass)
Inheritance
the derived class inherits the properties of the base class
Declaring a derived class
place “:” after derived class name, followed by a member access specifier like “public” and base class name
class DerivedClass:public BaseClass {…};
member access
Members of a derived class have access to the public members of the base class, but not to the private members of the base class
protected
private
public
protected - accessible by self and derived classes
private - only accessible by self
public - accessible by anyone
specifiers in the class definition
public - “public->public, protected->protected” - public members of base are accessible as public members of Derived and protected members of base are accessible as protected members of derived
protected - “public->protected, protected->protected” - public and protected members of base are accessible as protected members of derived
private - “public->private, protected->private” - public and protected member of base are accessible as private members of derived, this is the default if none of these are typed (class derived :base{..};)
override
When a derived class defines a member function with same name and parameters as a base class function, member function overrides the base class function
override vs overloading
Overloading has different parameters, derived function does not hide base function
Overriding, all the same
hasa vs isa
Has-a - object has an object, no inheritance
Is-a - object is a kind of object
Polymorphism
determining which program behavior to execute depending on data types
Compile-time polymorphism
when the compiler determines which function to call at compile time
Runtime polymorphism
when the compiler is unable to determine which function to call at compile time, so the determination is made while the program is running
derived/base class pointer conversion
where a pointer to a derived class is converted to a pointer to the base class without explicit casting
Virtual function
member function that may be overridden in a derived class and is used for runtime polymorphism
Declared by prepending the keyword “virtual”, ex virtual string GetDescription() const
At runtime, when a virtual function is called using a pointer, the correct function to call is dynamically determined based on the actual object type to which the pointer or reference refers
override
keyword -optional - indicate that a virtual function is overridden in a derived class