Академический Документы
Профессиональный Документы
Культура Документы
Car Bicycle
2-door 4-door
C++ and inheritance
• The language mechanism by which one class acquires the properties
(data and operations) of another class
• Base Class (or superclass): the class being inherited from
• Derived Class (or subclass): the class that inherits
Advantages of inheritance
• When a class inherits from another class, there are
three benefits:
• (1) You can reuse the methods and data of the
existing class
(2) You can extend the existing class by adding new
data and new methods
(3) You can modify the existing class by
overloading its methods with your own
implementations
Inheritance Concept
• Augmenting the original class
Polygon Point
ComplexNumber real
imag
10
Types of Inheritance
1. Single class Inheritance:
Class A
Class A
Class B Class C
Class D
virtual base classes
• Notion:
- keyword virtual locates before or behind the access specifier, but it must locate before the
base class name.
Output:
Base default constructor
Base default constructor
Derived default constructor
Base default constructor
Derived parameterized constructor
class Base
{
int x;
public:
Base(int i)
{
x = i;
cout << "Base Parameterized Constructor\n";
}
};
int main()
{
Derived d(10) ;
}
output: A:default
B test(1); B
27
Constructor Rules for Derived Classes
You can also specify an constructor of the base
class other than the default constructor
DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args )
{ DerivedClass constructor body }