Inheritance
Inheritance
Chapter - Inheritance
Prepared by Md.
Masum Billah
Lecturer, Dept. of CSE, CBST
Mobile: 01793200796
Inheritance
Q.1. What is inheritance?
Inheritance is the methodology of using properties and methods of an already existing class in a
new class. Inheritance promotes code reuse and the creation of a hierarchical relationship between
classes.
Base class: The class whose properties are inherited by sub class is called Base Class , Super class or
Parent Class.
Sub class: The class that inherits properties from another class is called Sub class or Derived Class
or Child Class.
Syntax of Inheritance
class base_class
{
//Body of base class
};
class derived_class : access_modifier base_class
{
//Body of derived class
};
Code Reuse: Inheritance allows us to reuse code by creating new classes based on existing ones.
This means we can inherit attributes and behaviors from a parent class, reducing the need for
redundant code.
Overriding: With inheritance, we will be able to override the methods of the base class. Thus we
can define the behaviour of that function again.
Polymorphism: Inheritance supports polymorphism. Here objects of different classes can be treated
as objects of a common base class. This allows for the creation of generic code that can work with
multiple types of objects.
Simplicity: Inheritance simplifies code structure and maintenance. Changes or updates can be made
in one place (the base class) and inherited by all subclasses.
Extensibility: we can extend the functionality of existing classes by creating new subclasses. This
allows us to add specialized features or modify behavior without altering the original class.
Q.3. what do you mean by inheritance path? Illustrate how constructors are invoked when the
classes are inherited.
In other words, it's the sequence of parent and child classes that shows how inheritance flows
within a program. Example: Vehicle -> Car -> ElectricCar.
#include
<iostream> using
namespace std;
class Base {
public:
Base() {
cout << "Base class constructor" << endl;
}
};
int main() {
Derived derivedObj; // Creating an object of the Derived
classreturn 0;
}
private: The private access modifier is specified using the keyword private.
The methods or data members declared as private are accessible only within the class in
which they are declared.
Any other class of same package will not be able to access these members.
protected: The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within same package or
sub classes in different package.
public: The public access modifier is specified using the keyword public.
The public access modifier has the widest scope among all other access modifiers.
Classes, methods or data members who are declared as public are accessible from
everywhere in the program. There is no restriction on the scope of a public data member.
Q.4. when a base class is publicly inherited as public by the derived class what happened to it
public and private members?
When a base class is publicly inherited as public by a derived class, the access specifiers of the base
class members determine how those members are accessible within the derived class. Here's what
happens to the public and private members:
Public Members: Public members of the base class remain public in the derived class. This means
that they can be accessed through the derived class.
Private Members: Private members of the base class remain private in the derived class. This means
that they cannot be directly accessed or used in the derived class, even though they have been
inherited.
Protected Members: Protected members of the base class remain protected and can be accessed by
the derived class and its subclasses. They are not directly accessible from outside the class hierarchy.
private:
int privateMemberBase;
};
When a base class is inherited as private by its derived class, both its public and private members
become private members of the derived class. Here's what happens:
Public Members: Public members of the base class become private members of the derived class.
This means that they can only be accessed within the scope of the derived class and are not
accessible from outside the derived class.
Private Members: Private members of the base class also become private members of the derived
class. Since private members are not accessible outside the class they are defined in, they are not
directly accessible in the derived class either.
Protected Members: Protected members of the base class also become private in the derived class.
They are only accessible within the derived class itself, just like private members.
Here's a visual representation of the inheritance and accessibility when the base class is inherited as
private:
class Base
{public:
int publicMemberBase;
private:
int privateMemberBase;
};
// Here, both publicMemberBase and privateMemberBase from Base become private in Derived
};
When a class can inherit the attributes of two or more classes this is known as multiple inheritance.
Syntax of Multiple Inheritance:
class A
{
// code of class A
}
class B
{
// code of class B
}
class C: public A, public B (access modifier class_name)
{
// code of the derived class
}
Q.7. Describe different form of inheritance.
1. Single Inheritance: One derived class inherits from one base class.
2. Multiple Inheritance: One derived class inherits from many base classes.
3. Multilevel Inheritance: One derived class inherits from other derived classes.
4. Hierarchical Inheritance: More than one derived classes inherit from one base class.
5. Hybrid Inheritance: A combination of more than one type of inheritance.
1. Single inheritance: Only one derived class inherited from only one base class is called single
inheritance.
Example: Let A is a base class
and B is a new class derived from A
Syntax:
class A {.............};
class B : Public A {..........};
2.Multiple inheritance: A class can inherit the attributes of two or more classes. This is known as
multiple inheritance.
Example :
Syntax:
Class D : public B1, public B2, private B3 // Access specifier can be public or private
{
(Body of D)
}
Example:
Syntax:
Class A { ….. };
Class B : Public A { ….. };
Class C : Private B{ ….. };
Syntax:
Class student { …… }; // base class,
Class Arts : Public student { ……};
Class Medical : Public student {…….};
Class Engineering : Public student { ……};
Class CSE : Public Engineering { ……. };
Class EEE : Public Engineering { …… };
Class ECE : Public Engineering { …… };
Example: In program:
Syntax:
Class student {……};
Class test : public student {……};
Class result : public test, public sports {…….};
Q.8. How does the properties of following two derived classes differ?
a) class D1 : private B{//};
b) class D2 : public B{//};
In the given code snippets, D1 and D2 are both derived classes from a base class B. The difference
between the two classes lies in the access specifier used during inheritance (private and public). Let's
break down the differences in terms of member accessibility and inheritance:
a) class D1 : private B { // };
In this case, D1 is inheriting from B using the private access specifier. This means that all the public
and protected members of class B will become private members of class D1. Private members are
only accessible within the class they are defined in and cannot be accessed through derived classes.
b) class D2 : public B { // };
In this case, D2 is inheriting from B using the public access specifier. This means that the public
members of class B will remain public in class D2, and the protected members of class B will
become protected members of class D2. Public and protected members can be accessed by the
derived class and outside the class.
Virtual base class is a class that is used as a base class for multiple derived classes in an
inheritance hierarchy, and it is declared as "virtual."
When to use:
The purpose of declaring a base class as virtual is to resolve the "diamond problem" that can occur
in multiple inheritance scenarios. Virtual Class is defined by writing a keyword “virtual” in the
derived classes, allowing only one copy of data to be copied to derived classes. It prevents multiple
instances of a class appearing as a parent class in the inheritance hierarchy when multiple
inheritances are used.
Example: (May skip this example)
class A
{public:
int data;
};
In this example, because both B and C inherit virtually from A, there is only one instance of A in the
object D, making it clear which 'data' member to access.
Q.10. what is protected use for?
The protected access modifier is used in object-oriented programming to control how classes and
their subclasses can access class members like variables and methods.
Inheritance: Protected members can be accessed by subclasses. This is useful because it allows
child classes to reuse and build upon the functionality of parent classes.
Encapsulation: It helps in encapsulation by restricting direct access to members from outside the
class but still allowing subclasses to access and use them.
Code Organization: It helps in organizing code by indicating which parts are meant to be used by
subclasses, making the code more maintainable and understandable.
Public Inheritance from B: This means that the public members of class B will remain public
members of class A, and the protected members of class B will remain protected members of class
A. However, the private members of class B will not be directly accessible in class A.
Private Inheritance from C: This means that both the public, private and protected members of
class C will become private members of class A. Essentially, class A can use the members of class C,
but they won't be accessible outside of class A.
Public Inheritance from C: This means that the public members of class C will remain public
members of class A, and the protected members of class C will remain protected members of class A.
The private members of class C won't be directly accessible in class A.
Protected Inheritance from B: This means that the public and protected members of class B will
become protected members of class A. The private members of class B won't be directly accessible
in class A.
Q. How visibility changes in derived class? ( )
Public mode:
When we inherit a derived class from a base class with public visibility mode, the public members
and protected members of the base class will be inherited as public members and protected members
respectively of the derived class.
Q13. How object of the derived class can access private members of base class? (Base class
can’t be modified)
In object-oriented programming, private members of a base class are not directly accessible by
objects of a derived class. Private members are completely hidden from outside classes, including
derived classes.
If we cannot modify the base class and need to access its private members within a derived class, we
have limited options:
1. Accessor Methods: If the base class provides public or protected methods that allow us to access
or manipulate its private members indirectly, we can use those methods in the derived class.
public:
int getPrivateValue()
{return
privateValue;
}
};
2. Friendship( Not Necessary ): If we have control over the derived class and need access to
privatemembers of the base class, we can declare the derived class as a friend of the base class. This
allowsthe derived class to access the private members of the base class, but it's a less common and
more invasive approach.
Example in C++:
class Base
{private:
int privateValue;
public:
friend class Derived;
};
class Derived
{ public:
void displayPrivateValue(Base&
base) {int value =
base.privateValue;
cout << "Private Value: " << value << endl;
}
};
When an object of one class is created into another class then that object will be a member of that
class, this type of relationship between the classes is known as containership.
Example:
// Container class
class second {
};
1. Is-A relationship: Whenever one class inherits another class, it is called an IS-A relationship.
Example:
class Animal {
public:
void eat() {
// Implementation of eating behavior
}
};
class Car {
private:
Engine carEngine; // Car "Has-A" Engine
public:
void drive() {
carEngine.start(); // Using the Engine object
// Implementation of driving the car
}
};
#include <iostream>
using namespace std;
void draw() {
cout << "Drawing a shape" << endl;
}
};
// Define a derived class that inherits from both Shape and Color
class Circle : public Shape, public Color
{public:
Circle() {
cout << "Circle constructor" << endl;
}
void print() {
cout << "This is a circle." << endl;
}
};
int main()
{ Circle circle;
circle.draw(); // Call method from the Shape base class
circle.fill(); // Call method from the Color base class
circle.print(); // Call method from the Circle derived class
return 0;
}
#include <iostream>
using namespace std;
return 0;
}
Output: Animal is eating.
Mammal gives birth to live young.
Dog is barking.
#include <iostream>
using namespace std;
// Base class
class Shape
{public:
void setDimensions(float length, float width)
{this->length = length;
this->width = width;
}
protected:
float length;
float width;
};
// Derived class 1
class Rectangle : public Shape
{public:
float area() override
{ return length *
width;
}
};
// Derived class 2
class Square : public Shape
{public:
float area() override
{ return length *
length;
}
};
int main()
{ Rectangle
rect;Square
square;
rect.setDimensions(5.0, 3.0);
square.setDimensions(4.0, 4.0);
return 0;
}