with C++ Lecture 9
Introduction to Inheritance and Function Overriding
1. Review of Inheritance
o Base Class: The original class from which others inherit.
o Derived Class: The class that inherits from the base class.
o Public inheritance allows the derived class to access public
and protected members of the base class.
2. Function Overriding
o Occurs when a derived class defines a function with the same
name and parameters as a function in its base class. This
allows the derived class to provide a specific implementation.
Example:
3. Calling Overridden Functions
, o The version of the function called depends on the type of
the object or pointer. For objects, the derived class's
version is called if the object is of the derived type.
Example:
The base class function can still be called using the scope
resolution operator.
Polymorphism
1. Concept and Importance
o Polymorphism allows objects of different classes to be treated
as objects of a common base class. It enables the invocation
of derived class methods through base class pointers or
references.
Example:
The output is "Message from base class" because the function
is bound at compile time based on the pointer type (CBase*).
2. Virtual Functions
o Virtual functions enable polymorphism by allowing derived
classes to override base class methods. The virtual keyword in
the base class function declaration signals the compiler to use
dynamic binding.
Example: