lab 3 oops

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 17

LAB NO.

3
27/09/2024

INHERITANCE IN C++

Lab outcomes:

After completing this lab, students will be able to:

 Understand Inheritance Concepts: Grasp the fundamentals of inheritance and


differentiate between various types (single, multiple, multilevel, hierarchical, and hybrid).
 Implement and Test Class Hierarchies: Build and test real-world models using
different types of inheritance, applying appropriate access specifiers.
 Resolve Inheritance Ambiguities: Manage ambiguity in multiple inheritance using
scope resolution and virtual inheritance techniques.
 Demonstrate Polymorphism: Implement polymorphic behavior through virtual
functions and understand the role of constructors/destructors in inheritance chains.

Corresponding CLO and PLO:


 CLO-2, PLO-3 (Design and Development of solution)

Theory:
Inheritance is one of the cornerstones of Object-Oriented Programming
(OOP) in C++. It allows a new class (derived class) to inherit properties and
behaviors from an existing class (base class). This mechanism enables code
reuse, extensibility, and the establishment of a relationship between classes,
facilitating the creation of more complex systems in a structured manner.
Below, we’ll dive deep into every aspect of inheritance, explaining how it
works and providing examples for each type of inheritance. In C++, we use
the : symbol to perform inheritance. For example,

What is Inheritance?
Inheritance in C++ allows you to create new classes based on existing
classes. This concept is central to OOP because it enables code reuse and
helps in maintaining and extending existing code without duplication. The
class that inherits properties is called the derived class, and the class from
which it inherits is known as the base class.
Purpose and Benefits of Inheritance
 Code Reusability: By inheriting from an existing class, you avoid
rewriting common functionality, reducing code duplication.
 Extensibility: You can extend existing classes with new features
without modifying the original class.
 Abstraction: Inheritance promotes abstract thinking, allowing you to
design more general classes and create specific classes based on
them.
 Polymorphism Support: It works closely with polymorphism to
enable dynamic binding of methods.

Syntax of Inheritance
The syntax for inheritance in C++ uses a colon (:) followed by an access
specifier (public, protected, or private) and the name of the base class:
class BaseClass {
// Members of the base class
};

class DerivedClass : accessSpecifier BaseClass {


// Members of the derived class
};
Here:
 BaseClass is the class being inherited.
 DerivedClass is the new class that inherits the properties and methods
from BaseClass.
 accessSpecifier defines how the members of the base class are
accessible in the derived class.
4. Access Specifiers in Inheritance
The access specifier controls how the members of the base class are
inherited in the derived class. It determines the visibility and accessibility of
inherited members:
 Public Inheritance (public):
o Public members of the base class remain public in the derived
class.
o Protected members of the base class remain protected in the
derived class.
o Private members of the base class are not accessible directly in
the derived class.
 Protected Inheritance (protected):
o Public and protected members of the base class become
protected in the derived class.
o Private members of the base class are still not accessible.
 Private Inheritance (private):
o Public and protected members of the base class become private
in the derived class.
o Private members of the base class remain inaccessible.
Example Code: Public Inheritance
#include <iostream>
using namespace std;

class Animal {
public:
void eat() {
cout << "Eating..." << endl;
}
};

class Dog : public Animal {


public:
void bark() {
cout << "Barking..." << endl;
}
};

int main() {
Dog dog;
dog.eat(); // Accessible due to public inheritance
dog.bark(); // Defined in Dog class
return 0;
}

5. Types of Inheritance
C++ supports several types of inheritance, each with its own characteristics.
Let's explore each type in detail with examples:

5.1 Single Inheritance


A derived class inherits from a single base class. This is the simplest form of
inheritance and is used when you want to extend the functionality of one
class.
Example Code
#include <iostream>
using namespace std;

class Person {
public:
void speak() {
cout << "Person is speaking..." << endl;
}
};

class Student : public Person {


public:
void study() {
cout << "Student is studying..." << endl;
}
};

int main() {
Student student;
student.speak(); // Inherited from Person
student.study(); // Defined in Student
return 0;
}

5.2 Multiple Inheritance


A derived class inherits from more than one base class. This type allows
combining functionalities from multiple sources, but it can also lead to
ambiguity if not managed properly.
Example Code
#include <iostream>
using namespace std;

class Engine {
public:
void start() {
cout << "Engine starting..." << endl;
}
};

class Wheels {
public:
void roll() {
cout << "Wheels rolling..." << endl;
}
};

class Car : public Engine, public Wheels {


public:
void drive() {
cout << "Car driving..." << endl;
}
};

int main() {
Car car;
car.start(); // Inherited from Engine
car.roll(); // Inherited from Wheels
car.drive(); // Defined in Car
return 0;
}

Managing Ambiguity in Multiple Inheritance


If two base classes have methods with the same name, ambiguity arises
when calling these methods from the derived class. To resolve this, you need
to specify the base class using the scope resolution operator (::).
Example Code: Resolving Ambiguity
class Base1 {
public:
void display() {
cout << "Display from Base1" << endl;
}
};

class Base2 {
public:
void display() {
cout << "Display from Base2" << endl;
}
};

class Derived : public Base1, public Base2 {


public:
void show() {
Base1::display(); // Resolve ambiguity
Base2::display(); // Resolve ambiguity
}
};

int main() {
Derived obj;
obj.show();
return 0;
}
5.3 Multilevel Inheritance
A class derives from another derived class, forming a chain of inheritance.
Example Code
#include <iostream>
using namespace std;

class LivingBeing {
public:
void breathe() {
cout << "Breathing..." << endl;
}
};

class Animal : public LivingBeing {


public:
void move() {
cout << "Animal is moving..." << endl;
}
};

class Bird : public Animal {


public:
void fly() {
cout << "Bird is flying..." << endl;
}
};

int main() {
Bird bird;
bird.breathe(); // Inherited from LivingBeing
bird.move(); // Inherited from Animal
bird.fly(); // Defined in Bird
return 0;
}

5.4 Hierarchical Inheritance


Multiple derived classes inherit from the same base class. It allows creating
multiple specialized versions of a class.
Example Code
#include <iostream>
using namespace std;

class Shape {
public:
void draw() {
cout << "Drawing shape..." << endl;
}
};

class Circle : public Shape {


public:
void drawCircle() {
cout << "Drawing circle..." << endl;
}
};

class Square : public Shape {


public:
void drawSquare() {
cout << "Drawing square..." << endl;
}
};

int main() {
Circle circle;
Square square;
circle.draw(); // Inherited from Shape
circle.drawCircle(); // Specific to Circle

square.draw(); // Inherited from Shape


square.drawSquare(); // Specific to Square
return 0;
}

5.5 Hybrid Inheritance


A combination of two or more types of inheritance (e.g., multiple and
multilevel). It can lead to the diamond problem when the same base class is
inherited multiple times through different paths.
6. Virtual Inheritance
Virtual inheritance is used to prevent multiple "instances" of a base class
when using hybrid inheritance. This resolves the diamond problem, ensuring
that only one copy of the base class members is inherited.
Example Code: Diamond Problem Resolution
#include <iostream>
using namespace std;
class Animal {
public:
void makeSound() {
cout << "Animal sound..." << endl;
}
};

class Mammal : virtual public Animal {};


class Bird : virtual public Animal {};

class Bat : public Mammal, public Bird {};

int main() {
Bat bat;
bat.makeSound(); // No ambiguity due to virtual inheritance
return 0;
}

7. Constructors and Destructors in Inheritance


When an object of a derived class is created:
 The constructor of the base class is called first, followed by the
constructor of the derived class.
 The destructor of the derived class is called first, followed by the
destructor of the base class when the object goes out of scope.

Example Code: Constructor and Destructor


#include <iostream>
using namespace std;

class Base {
public:
Base() {
cout << "Base class constructor called." << endl;
}
~Base() {
cout << "Base class destructor called." << endl;
}
};
class Derived : public Base {
public:
Derived() {
cout << "Derived class constructor called." << endl;
}
~Derived() {
cout << "Derived class destructor called." << endl;
}
};

int main() {
Derived obj;
return 0;
}

8. Summary
Inheritance in C++ is a powerful tool that supports the creation of complex
and reusable class hierarchies. Understanding its different forms (single,
multiple, multilevel, hierarchical, hybrid) and managing ambiguity (using
virtual inheritance) is crucial for efficient OOP programming.

Tasks 1:
Lab task 1: Write a program that has a class named BankAcnt that
have the properties of a simple bank account. Then inherit its
properties to SavingAcnt and CurrentAcnt Classes with their extra
features. Ask user for all account details.
Code:
Output:
Lab task 2: A car show room needs a software for listing their
vehicles, vehicles type and spare parts. There has to be all features
included that a vehicle have. Solve this problem using inheritance.
Code:
Output:

Observations:
In this lab we have learned about the parent of child class and we learned 5
parts of inheritance and how can we use it in our program and how can we
link them with each other and after that we learned how to access their
private or public members and we learned the there are three types of class
public, protected, private and after that we done some tasks.
Rubrics
Report not Content that The The Appropri Conclusion
submitted has been requirement observati ate drawn
plagiarized s are ons, as measure correctly
or that has described,
well as ments or with exact
Laborato been as well as
submitted the the numeric results and
ry
incompletel experiment complete al a complete
Reports
y al process. technique analysis report in
, are are every way
document carried
ed. out.
Category Ungrade Very Poor Poor Fair Good Excellent
d
Marks 0 1 2 3 4 5

Date Total Instructor’s Signature


Marks

Demonst Absent The The student The The student The student
ration student understands student has created successfully
is unable the followed a functional developed a
to presented instructio or working functional
adequat laboratory ns to build schematic, model,
ely instructions the core model, logic, circuit,
follow and is schematic block block
the familiar with , block diagram, or diagram, or
instructi the lab diagram, code and code and
ons environment code, or has completed
provided but Cannot model. successfull the lab
. The setup With y run the objective in
student simulation some program or real-time or
can according to assistance circuit on a in a
name design but , the software simulation
the knows how student platform. environment
hardwar to perform can set up With , achieving
e or simulation and run minimum the expected
simulatio the assistance, results. They
n simulation they can can set up,
platform, . On the set up and operate, and
but protoboar run the run the
Cannot d/trainer/s simulation. simulation
setup or imulation on their own.
perform software
the
simulatio
n
Category Ungrad Very Poor Fair Good Excellent
ed Poor
Marks 0 1 2 3 4 5

Date Total Instructor’s


Marks Signature

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy