Inheritance is a feature in which you can have a class inherit variables and methods from another class without writing them over and over from scratch.
operator ":" is used to specify inheritance
In the class header you inherit the definition
Derived : Parent
The derived constructor will call the default parent constructor if you declare the constructor naked. Same for the destructor.
it is possible for the derived constructor to call the initialized parent constructor with the operator ":" in the implementation.
The parent constructor will be called BEFORE the derived constructor.
The parent destructor will be called AFTER the derived destructor.
This is valid for methods as well. You can have two methods with the same name in derived and parent class, and the derived implementation will be favored.
Example.
In your program you need to handle humans and students.
Humans have several characteristics. Name, age and gender.
Students have several characteristics. Name, age, gender and id.
Student has all the characteristics of a human with some additions.
Inheritance allows the class student to inherit all the variables and methods from the class human while adding some that are unique to the class student.
Full code
First I define the parent class with header and implementation.
Parent Class Header
XXX
Parent Class Implementation
XXX
With this I defined the class human with the characteristics Name, age and gender.
Now to Make the class student I can Inherit Name, age and gender from the parent class human, while adding just variables and handler for the last characteristic the id which is unique to the Derived class
Derived Class Header
END
Derived Class Implementation
END
No comments:
Post a Comment