Lecture 6
Lecture 6
Lecture 6
Programming
Today’s Lecture
1. Introduction to Inheritance.
• The derived classes have all the features of the base class and the
programmer can choose to add new features specific to the newly
created derived class.
C++ Inheritance
Advantages of inheritance
When a class inherits from another class, there are three main 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
C++ Inheritance
Reusability:
Inheritance helps the code to be reused in many situations.
General Syntax:
The above makes sample have access to both public and protected variables of base
class MyClass
Rules for building a class
hierarchy
• Derived classes are special cases of base classes
• A derived class can also serve as a base class for new classes.
• There is no limit on the depth of inheritance allowed in C++ (as far as
it is within the limits of your compiler)
• It is possible for a class to be a base class for more than one derived
class
Inheritance and
accessibility
• A class inherits the behavior of another class and
enhances it in some way
• Inheritance does not mean inheriting access to
another class’ private members
Access Control/ Visibilty
modes and Inheritance:
• A derived class can access all the non-private
members of its base class. Thus base-class
members that should not be accessible to the
member functions of derived classes should be
declared private in the base class.
• We can summarize the different access types
according to who can access them in the following
way:
Access Control and
Inheritance:
Visibility Modes in Inheritance
Reminder about public, private and protected access
specifiers:
Create a class Employee with the following attributes and member functions:
Employee registration number
Employee name
Destination
Basic salary
Profitable fund
Get the function set_ data of the registration number, name, and destination.
Inherit (public) a class salary from the employee. Salary should contain the
following member functions:
Get function of basic salary, and calculate 10% of profitable fund of basic
salary.
Get sum function to calculate basic salary and profitable fund.
Header.h
class emp { void emp::set_data()
public: {
int reg_no; cout << " Enter your
char name[20]; registration number: ";
char dest[20]; cin >> reg_no;
int b_salary; cout << " Enter your name: ";
int p_f; cin.ignore();
cin.getline(name,20);
void set_data(); cout << " Enter your
destination: ";
}; cin.getline(dest, 20);
}
int main()
{
emp object1;
salary object2;
int basic;
object2.set_data();
cout << " Enter your basic salary: ";
cin >> basic;
object2.set_salary(basic);
object2.sum();