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

OOPS2

Object Oriented Programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

OOPS2

Object Oriented Programming
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 47

Programming with C++ (Open Elective-II)

Inheritance Introduction,
benefits,
Access specifiers,
Types of inheritance –
single, multiple,
multilevel,
hybrid and hierarchical.

Case Study: Write a program in c++ to derive


class bicycle from class vehicle with appropriate
syntax
INHERITANCE
It is the Process of creating a New class from
an existing class.

The Existing class is called Base or Parent


class.

The New class is called as Child or Derived


Class
Introductio
n
Base Class/ Class: Vehicle
Parent
Class

Derived Car Truck


Classes/ Sub
Class
Advantages
• It permits code reusability. So, save time and increase

the program reliability.

• A programmer can use a class created by another


person or company without modifying it derive other
classes from it that are suited to particular situations

• Improve Program Reliability

• It Permits code sharing


Advantages
• The base class need not be changed but can be

adapted to suit the requirements in different


applications.

• Saves developers time and effort so that they need


not to spend time to know the core technical facts
Syntax of Inheritance in C++
class derived_class_name : access-specifier base_class_name
{
// body ....Syntax
};

where,
class: keyword to create a new class

derived_class_name: name of the new class, which will inherit the base class

access-specifier: Specifies the access mode which can be either of private,


public or protected. If neither is specified, private is taken as default.

base-class-name: name of the base class.


Access Control and Inheritance

•Example:
1.class ABC : private XYZ //private derivation
•{ }
2.class ABC : public XYZ //public derivation
•{ }
3.class ABC : protected XYZ //protected derivation
•{ }
4.class ABC: XYZ //private derivation by default
• { }
Public, Protected, and Private inheritance in C++
public, protected, and private inheritance have the following features:

• public inheritance makes public members of the base class public


in the derived class, and the protected members of the base class
remain protected in the derived class.

• protected inheritance makes the public and protected members of


the base class protected in the derived class.

• private inheritance makes the public and protected members of


the base class private in the derived class.
Sub Class: The class that
inherits properties from
another class is called
Subclass or Derived Class.

Super Class:The class whose


properties are inherited by
subclass is called Base Class
or Super class.
Access Control and Inheritance
A derived class can access all the non-private members of its base
class
We can summarize the different access types according to - who can
access them in the 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. following way −

Access public protected private


Same class yes yes yes
Derived classes yes yes no
Outside classes yes no no
Access Control and
Inheritance
There are three Access specifiers in C++. These are:
public – members are accessible from outside the
class, and members can be accessed from anywhere.
private – members cannot be accessed (or viewed)
from outside the class, i.e members are private to
that class only.
protected – members cannot be accessed from
outside the class, but, they can be accessed in
inherited classes or derived classes.
Access Control and Inheritance
● When a base class is privately inherited by the derived class, public
members of the base class becomes the private members of the
derived class and therefore, the public members of the base class
can only be accessed by the member functions of the derived class.
They are inaccessible to the objects of the derived class.

● On the other hand, when the base class is publicly inherited by the
derived class, public members of the base class also become the
public members of the derived class. Therefore, the public members
of the base class are accessible by the objects of the derived class as
well as by the member functions of the derived class.
Visibility of Inherited
Members
Base class Derived class visibility
visibility
Public Private Protected

Private Not Inherited Not Inherited Not Inherited

Protected Protected Private Protected

Public Public Private Protected


Types of Inheritance

1. Single inheritance
2. Multilevel
inheritance
3. Multiple inheritance
4. Hierarchical
inheritance
5. Hybrid inheritance
Types of Inheritance

1. Single Inheritance: In single inheritance,


a class is allowed to inherit from only one
class.
i.e. one subclass is inherited by one base
class only.
Syntax:
class subclass_name : access_mode base_class
{
// body of subclass
};
SingleInheritance class Child : public Parent
{
public:
class Parent int id2;
{ void printID_c()
public: {
int id1; cout << "Child ID: " << id2 ;
void printID_p() }
{ };
cout << "BaseID: " << id1 ; int main()
} {
}; Child o;
o.id1 = 7;
o.printID_p();
o.id2 = 91;
o.printID_c();
return 0;
}
Multilevel Inheritance: When one class inherits
another class which is further inherited by another class,
it is known as multi level inheritance in C++.
Inheritance is transitive so the last derived class acquires
all the members of all its base classes.

Syntax:
class A

{ ...........};
class B : access_specifier A

{ ...........} ;

class C : access_specifier B
{ ...........} ;
Example: Multilevel Inheritance
class Animal class Dog1: public Dog {
{
public:
public:
void weep() {
void eat()
{ cout<<"Eating..."<<endl; cout<<“Crying...";
} }
}; };
class Dog: public Animal int main(void) {
{ Dog1 d;
public:
void bark() d.eat();
{ cout<<"Barking..."<<endl;
} d.bark();
}; d.weep(); return 0;}
• class A { • // derived from class derive1
• Public: int a; • class C : public B {
• void get_A_data() • Private: int c;
• { • public:
• cout << "Enter value of a: "; void get_C_data()
• cin >> a; • {
• } • cout << "Enter value of c: ";
• }; • cin >> c;
// derived class from base class • }
• class B : public A { • void sum()
• Public: int b; • {
• void get_B_data() • int ans = a + b + c;
• { • cout << "sum: " << ans;
• cout << "Enter value of b: "; • }
• cin >> b; • };
• }
• int main()
• {
• // object of sub class
• C o;
• o.get_A_data();
• o.get_B_data();
• o.get_C_data();
• o.sum();
• return 0;
• }
#include <iostream>
using namespace std;

class A {
public:
void display() {
cout<<"Base class content.";
}
};

class B : public A {};

class C : public B {};

int main() {
C obj;
obj.display();
return 0;
}
Multiple Inheritance: Multiple Inheritance is a feature of C++ where
a class can inherit from more than one class. i.e one subclass is
inherited from more than one base class.
Syntax:
class subclass_name : access_mode base_class1, access_mode base_class2,
....
{
// body of subclass
};
#include<iostream.h> class deri:public base1,public
class base1 base2
{ {
protected : private:
int var1; int var3;
public : public :
void disp_base1() { deri(int a,int b,int c)
cout<<"var1 "<<var1<<endl; {
}}; var1=a;
class base2 var2=b;
{ var3=c;
protected : }
int var2; void disp_me()
public : {
void disp_base2() cout<<"var3 is"<<var3;
{ } };
cout<<"var2 is"<<var2<<endl;
void main()
{
deri d(10,20,30);
clrscr();
d.disp_base1();
d.disp_base2();
d.disp_me();
getch();
}
Ambiguity in multiple inheritance &
multipath inheritance
● In multiple inheritances, when one class is derived from two
or more base classes then there may be a possibility that the
base classes have functions with the same name, and the
derived class may not have functions with that name as
those of its base classes.

● If the derived class object needs to access one of the


similarly named member functions of the base classes then it
results in ambiguity because the compiler gets confused
about which base’s class member function should be called
• class base1
• {
• public:
• void someFunction( )
• {....}
• };
• class base2
• {
• void someFunction( )
• {....}
• };
• class derived : public base1, public base2
• {
• };
• int main()
• { derived obj;
• obj.someFunction() // Error! }
This problem can be solved using the scope resolution
function to specify which function to class
either base1 or base2.

• int main()
•{
• obj.base1::someFunction( ); // function of base1 class
is called
• obj.base2::someFunction(); // function of base2 class is
called.
• }
Hybrid Inheritance: Hybrid inheritance or multipath inheritance is
combination of two or more inheritances such as
single,multiple,multilevel or Hierarchical inheritances.
Class A
{
statement(s)
};
Class B: public A
{
statement(s);
};
Class C
{
statement(s);
};
Class D: public B, public C
{
statement(s);
};
Class A
{
statement(s);
};
Class B: public A
{
statement(s);
};
Class C: public B
{
statement(s);
};
Class D: public B
{
statement(s);
};
#include <iostream>
using namespace std;
class A { // Base class A // Derived class D from both class B and
public: class C (hybrid inheritance)
void displayA() {
cout << "Class A" << endl; class D : public B, public C {
} public:
}; void displayD()
{
class B { // Base class B cout << "Class D (derived from B and C)“ ;
public: }
void displayB() { };
cout << "Class B" << endl; int main() {
} D d;
}; d.displayA(); // Method from class A
class C : public A // Derived C from A d.displayB(); // Method from class B
{ d.displayC(); // Method from class C
public: d.displayD(); // Method from class D
void displayC() {
cout << "Class C (derived from A)“; return 0;
} }
};
• Class A is a base class with a function displayA()

• .Class B is another base class with a function displayB().

• Class C inherits from Class A and has its own function


displayC().

• Class D inherits from both Class B and Class C (thus


from Class A indirectly), making it an example of hybrid
inheritance.
• The main() function creates an object of Class D and calls
the display functions from all the base and derived classes.
Hierarchical Inheritance: Syntax of Hierarchical
Inheritance:
Hierarchical inheritance is defined as the class A
process of deriving more than one class {
// body of the class A.
from a base class. }
class B : public A
{
// body of class B.
}
class C : public A
{
// body of class C.
}
class D : public A
{
// body of class D.
}
Inheritance

Class Employee
Common to
Name Director

Age
Manager
Employee id
Salary
Department Secretary

Clerk
Example: Hierarchical Inheritance
class Shape {
int main()
public:
{
int a; int b;
Rectangle r;
void get_data(int n,int m)
Triangle t;
{ a= n; b = m;
int length,breadth,base,height;
}
cout << "Enter the length and breadth";
};
cin>>length>>breadth;
class Rectangle:public Shape {
r.get_data(length,breadth);
public:
int m = r.rect_area();
int rect_area()
cout << "Area of the rectangle is : "
{
<<m<<endl;
int result = a*b;
cout << "Enter the base and height of the
return result;}};
triangle: " <<endl;
class Triangle : public Shape
cin>>base>>height;
{
t.get_data(base,height);
public:
t.triangle_area();
void triangle_area()
return 0;}
{
float result = 0.5*a*b; cout<< result;}
};
class manager :public employee
class employee {
{ float basic;
private : public :
int empno; float salary, da, hra,cca, pf;
char empname[20]; void getdata()
public : {
void getdata() employee::getdata();
{ cout<<"Enter Basic Salary \n";
cout<<"\n Enter Employee No"; cin>>basic;
cin>>empno; }
cout<<"\n Enter Employee name "; void putdata()
cin>>empname; {
da=0.30*basic;
} hra=0.15*basic;
void putdata() cca=0.05*basic;
{ pf=0.12*basic;
cout<<"\n Employee No"<<empno; salary=basic+da+hra+cca+-pf;
cout<<"\n Employee name "<<empname; employee::putdata();
} cout<<endl<<salary;
}; }
};
class supervisor : public employee
{ int main()
public : {
float salary; manager m;
float wages; supervisor s;
float incentive; m.getdata();
void getdata() s.getdata();
{ //w.getdata();
employee::getdata(); //w.putdata();
cout<<"\n Enter wages & incentives"; s.putdata();
cin>>wages>>incentive; m.putdata();
} return 0;
void putdata() }
{
salary=wages+incentive;
employee::putdata();
cout<<endl<<salary;
}
};
• Transportation
• Description:
• Create a base class Transport with an attribute capacity.
• Derive classes Bus and Car from Transport.
• Add an attribute routeNumber to Bus
• and model to Car.
• Implement functions to display the details of each
transport.
Problem : Banking System
• Description: Design a base class BankAccount with
attributes such as accountNumber, balance, and
ownerName.
• Derive classes SavingsAccount and CurrentAccount from
BankAccount.
• SavingsAccount should have an additional attribute for
interestRate,
• and CurrentAccount should have an attribute for
overdraftLimit.
• Implement methods to deposit and withdraw money
while enforcing the specific rules for each account type.
• Food Categories
• Description:
• Design a base class Food with attributes name and
calories.
• Derive classes Fruit and Vegetable from Food.
• Add an attribute season to Fruit and color to Vegetable.
• Implement functions to display food details.
• Problem : Academic Inheritance
• Description: Implement a base class School with
attributes like schoolName and location.
• Derive a class Teacher from School with attributes
teacherName and subject.
• Further, derive a class ClassTeacher from Teacher with
attributes classGrade and numStudents.
• Implement functions to display class teacher details.
• Organization Hierarchy
• Description: Create a base class Person with attributes like
name and age.
• Derive a class Employee from Person with attributes
employeeID and department.
• Further, derive a class Manager from Employee with attributes
teamSize and bonus.
• Implement methods to display information about the manager.
• Vehicle Hierarchy
• Description: Create a base class Vehicle with attributes like
make, model, and year.
• Derive classes Car and Bike from Vehicle.
• Car should have additional attributes like numDoors and
fuelType,
• while Bike should have type (sports, cruiser, etc.) and
engineCapacity.

• Implement functions to display the details of each vehicle.


• Vehicle Service System
• Description: Create a base class Vehicle with attributes
make and model.

• Derive two classes Car and Truck from Vehicle.



• Then, create a class HybridTruck that inherits both Car
and Truck.

• Implement functions to display details and compute the


fuel efficiency for the HybridTruck.

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