0% found this document useful (0 votes)
10 views

Inheritance

OOP inheritance

Uploaded by

basur00basur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Inheritance

OOP inheritance

Uploaded by

basur00basur
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

College of Business, Science &Technology (CBST), Mymensingh

Department of Computer Science and Engineering


Object Oriented Programming (OOP)

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
};

Q.2. Write down the importance of inheritance.

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.

An inheritance path, referred as an inheritance hierarchy or inheritance chain. It is a sequence of


classes connected by inheritance relationships.

In other words, it's the sequence of parent and child classes that shows how inheritance flows
within a program. Example: Vehicle -> Car -> ElectricCar.

How constructors are invoked when the classes are inherited:


When classes are inherited, the constructors are called in the same order as the classes are inherited.
If we have a base class and one derived class that inherits this base class, then the base class
constructor (whether default or parameterized) will be called first followed by the derived class
constructor.

The following program demonstrates the order of constructors in inheritance-

#include
<iostream> using
namespace std;
class Base {
public:
Base() {
cout << "Base class constructor" << endl;
}
};

class Derived : public


Base {public:
Derived() {
cout << "Derived class constructor" << endl;
}
};

int main() {
Derived derivedObj; // Creating an object of the Derived
classreturn 0;
}

Output: Base class constructor


Derived class constructor

Q. What are the different types of access modifiers/ visibility specifies?

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.

Specifiers Same Class Derived Class Outside Class


public Yes Yes Yes
protected Yes Yes No
private Yes No No

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.

Here's a visual representation of the inheritance and accessibility:


class Base
{public:
int publicMemberBase;

private:
int privateMemberBase;
};

class Derived : public Base {


// Here, publicMemberBase remains public
// privateMemberBase remains private (inaccessible)
};
Q.5. If the base is inherited as private by its derived class what happens to its public and
private members?

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;
};

class Derived : private Base {

// Here, both publicMemberBase and privateMemberBase from Base become private in Derived

};

Q.6. Describe the syntax of multiple inheritance with simple example.

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)
}

3.Multilevel inheritance: Multilevel inheritance is a type of inheritance where a class inherits


properties and behaviors from another class, and then another class inherits from that derived class.
In multilevel inheritance, there is a chain of inheritance with each class building upon the one before
it.

Example:
Syntax:
Class A { ….. };
Class B : Public A { ….. };
Class C : Private B{ ….. };

4.Hierarchical inheritance: It is a type of inheritance where a single base class is inherited by


multiple derived classes. In hierarchical inheritance, each of the derived classes inherits the
properties and behaviors (attributes and methods) of the base class, forming a tree-like structure.

Example: This design is implemented in program as follows:

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 { …… };

5.Hybrid inheritance: Hybrid inheritance is a combination of multiple types of inheritance within a


single program. It combines different inheritance types, such as single inheritance, multiple
inheritance, hierarchical inheritance, and multilevel inheritance, to achieve a specific design or
functionality.

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.

Q.9. What is virtual base class? When do we make a class virtual?

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;
};

class B : virtual public A {


};

class C : virtual public A {


};

class D : public B, public C {


};
int main()
{D d;
d.data = 42; // This is unambiguous due to virtual inheritance.
return 0;
}

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.

Q11. What is the implication of the following two definitions?


A) Class A: public B, private C{ // };
B) Class A: public C, protected B{ // };

a) Class A: public B, private C{ // };


In this case, class A inherits class B publicly and class C privately. Here's what this means:

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.

b) Class A: public C, protected B{ // };


In this case, class A inherits class C publicly and class B in protected mode. Here's what this means:

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? ( )

Q12. Describe the visibility chart for inheritance.

There are total 3 types of visibility mode in C++ that are:


 Public visibility mode,
 Protected visibility mode,
 Private visibility mode

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.

Protected visibility mode:


When we inherit a derived class from a base class with protected visibility mode the protected and
public members of the base class become protected members of the derived class
Private visibility mode:
When we inherit a derived class from the base class with private visibility mode then the public and
protected members of the base class become private members 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.

Here's an example in C++:


class Base
{private:
int privateValue;

public:
int getPrivateValue()
{return
privateValue;
}
};

class Derived : public


Base {public:
void displayPrivateValue() {
int value = getPrivateValue();
cout << "Private Value: " << value << endl;
}
};

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;
}
};

Q14. What is Containership? How does it differ from inheritance?

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:

// Class that is to be contained


class first {

cout<<”This is class first”;


};

// Container class
class second {

// Creating object of first


first f;

};

How does it differ from Inheritance-


1. Inheritance is the ability for a class to inherit properties and behavior from a parent class by
extending it, while Containership is the ability of a class to contain objects of different classes as
member data.
2. In inheritance all the public and protected properties/behavior of superclass may be overridden
in the subclass. But if a class is contained in another, the container does not get the ability to change
or add behavior to the contained.

3. Inheritance represents an “is-a” relationship in OOP, but Containership represents a “has-a”


relationship.

Q.What is Is-A Relationship and HAS-A Relationship?

In OOP we have two types of relationship:

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 Dog : public Animal {


public:
void bark() {
// Implementation of barking behavior
}
};
2. Has-A relationship: Whenever an instance of one class is used in another class, it is called
HAS-A relationship.
Example:
class Engine {
public:
void start() {
// Implementation of starting the engine
}
};

class Car {
private:
Engine carEngine; // Car "Has-A" Engine

public:
void drive() {
carEngine.start(); // Using the Engine object
// Implementation of driving the car
}
};

Q15. Sample program to introduce multiple inheritance.

#include <iostream>
using namespace std;

// Define the first base class


class Shape {
public:
Shape() {
cout << "Shape constructor" << endl;
}

void draw() {
cout << "Drawing a shape" << endl;
}
};

// Define the second base class


class Color {
public:
Color() {
cout << "Color constructor" << endl;
}
void fill() {
cout << "Filling with color" << 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;
}

Output: Shape constructor


Color constructor
Circle constructor
Drawing a shape
Filling with color
This is a circle

Q16. Sample program to introduce multilevel inheritance.

#include <iostream>
using namespace std;

// Define the base class


class Animal {
public:
void eat() {
cout << "Animal is eating." << endl;
}
};
// Define a derived class that inherits from Animal
class Mammal : public Animal {
public:
void giveBirth() {
cout << "Mammal gives birth to live young." << endl;
}
};
// Define another derived class that inherits from Mammal
class Dog : public Mammal {
public:
void bark() {
cout << "Dog is barking." << endl;
}
};
int main()
{Dog dog;

dog.eat(); // Call method from Animal base class


dog.giveBirth(); // Call method from Mammal base class
dog.bark(); // Call method from Dog derived class

return 0;
}
Output: Animal is eating.
Mammal gives birth to live young.
Dog is barking.

Q17. Write a C++ program to illustrate hierarchical inheritance.

#include <iostream>
using namespace std;

// Base class
class Shape
{public:
void setDimensions(float length, float width)
{this->length = length;
this->width = width;
}

virtual float area() {


return 0; // Base class implementation
}

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);

cout << "Area of Rectangle: " << rect.area() << endl;


cout << "Area of Square: " << square.area() << endl;

return 0;
}

Output: Area of Rectangle: 15


Area of Square: 16

You might also like