Unit 2 Complete

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 55

Object-Oriented Programming

Using C++
(CAP444)
Inheritance: reusability

father mother

child
Contact List
Students

Students in Attendance Module

Same Students in CA Module


Inheritance
One class can be derived from other class.
We can make the relationship between the classes.
We can re-use the functionality of classes
We can use different form of inheritance
Base Class

Derived Class
Inheritance: types of inheritance

A A A B

B
B

C
Single C

Multilevel
Multiple
A A

B C B C

Hierarchical Inheritance

Hybrid Inheritance
Single inheritance:
Syntax:
class derive_class_name : access_mode base_class_name
{
//body of derive_class
};
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.
Note: A derived class doesn’t inherit access to private data members. However, it does inherit a full parent
object, which contains any private members which that class declares.
Inheritance : Example 1
Base/Parent Class Derived/Child Class Main Function
#include <iostream> // Sub class inheriting // main function
using namespace std; from Base Class(Parent) int main()
  class Child : public Parent {
// Base class {     Child obj1;
class Parent { public:  
public:     int id_c;     // An object of class child has all
     int id_p; };
}; // data members and member functions
 
// of class parent
    obj1.id_c = 7;
    obj1.id_p = 91;
    cout << "Child id is: "
cout << obj1.id_c << '\n';
    cout << "Parent id is: "
cout << obj1.id_p << '\n';
 
    return 0;
}
Inheritance : Example 2
Base/Parent Class Derived/Child Class

#include<iostream> class Student: private Person


using namespace std; {
class Person     char course[50];
{     int fee;
    int id;     public:
    char name[100];     void set_s()
    public:         {
        void set_p()             set_p();
        {             cout<<"Enter the Course Name:";
            cout<<"Enter the Id:";             cin.getline(course,50);
            cin>>id;             cout<<"Enter the Course Fee:";
            cout<<"Enter the Name:";             cin>>fee;
            cin.get(name,100);         }         
        }            void display_s()
        void display_p()         {
        {             display_p();
            cout<<endl<<id<<"\t"<<name<<"\t";             cout<<course<<"\t"<<fee<<endl;
        }         }
}; };
Inheritance : Example 2 Cont...
int main()
{
    Student s; // child object
    s.set_s();
    s.display_s();
    return 0;
}
Output:
Inheritance : Modes of Inheritance

1. Public Mode: If we derive a subclass from a public base class. Then the public
member of the base class will become public in the derived class and protected
members of the base class will become protected in the derived class.

2. Protected Mode: If we derive a subclass from a Protected base class. Then both
public members and protected members of the base class will become protected in
the derived class.

3. Private Mode: If we derive a subclass from a Private base class. Then both
public members and protected members of the base class will become Private in the
derived class.
Inheritance : Modes of Inheritance (Example)
Child
class B : public A {
    // x is public
Parent     // y is protected
    // z is not accessible from B
class A { };
public:
    int x;
class C : protected A {
 
    // x is protected
protected:
    // y is protected
    int y;
    // z is not accessible from C
 
};
private:
    int z;
}; class D : private A // 'private' is
default for classes
{
    // x is private
    // y is private
    // z is not accessible from D
};
Inheritance : Modes of Inheritance (Table Summary)

Note: The private members in the base class cannot be directly accessed in


the derived class, while protected members can be directly accessed. 
Types of Inheritance
C++ Supports all types of Inheritance, Total five types :
1.Single inheritance
2.Multilevel inheritance
3.Multiple inheritance
4.Hierarchical inheritance
5.Hybrid 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.
Single inheritance Example
Result
ExamType
ExamStatus

getResult()

Student
Regno,
Name,
Marks
getStudentDetails()
Single Inheritance : Example Code 1
#include<iostream> // main function
using namespace std; int main()
  {  
// base class     // Creating object of sub class will
class Vehicle {     // invoke the constructor of base class
  public:     Car obj;
    Vehicle()     return 0;
    { }
      cout << "This is a Vehicle\n";
    }
};

// sub class derived from a single base class Output:


class Car : public Vehicle {
public:
    Car()
    {
      cout << “Car is a Vehicle\n";
    }
};
To Explicitly call base class constructor in derived class

#include <iostream>
using namespace std;

class MyBaseClass {
public:
MyBaseClass(int x) {
cout << "Constructor of base class: " << x << endl;
} Output:
}; Constructor of base class: 50
Constructor of derived class: 100
class MyDerivedClass : public MyBaseClass {
public:
MyDerivedClass(int y) : MyBaseClass(50) {
cout << "Constructor of derived class: " << y << endl;
}
};

int main() {
MyDerivedClass derived(100);
}
Single Inheritance : Example Code 2
#include<iostream> class B: public A
using namespace std; {
    int b, p;
class A     public:
{         void set_B()
    protected:         {
    int a;                set_A();
    public:             cout<<"Enter the Value of B=";
        void set_A()             cin>>b;
        {         }
            cout<<"Enter the Value of A=";         void cal_product()
            cin>>a;         {
        }             p=a*b;
 };             cout<<endl<<"Product of "<<a<<" * "<<b<<“= ”;
cout <<p;
        }      
int main() };
{
    B obj;
    obj.set_B();
    obj.cal_product();
    return 0;
}
Types of Inheritance
2. 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.

Note: Here, the number of base classes will be separated by a comma (‘, ‘) and the access mode
for every base class must be specified. 
Multiple inheritance Example

student
Multiple Inheritance : Example Code 1
#include <iostream> // second base class
using namespace std; class FourWheeler {
  public:
// first base class     FourWheeler()
class Vehicle {     {
public:         cout << "This is a 4 wheeler Vehicle\n";
    Vehicle() {     }
cout << "This is a Vehicle\n"; } };
};

// sub class derived from two base classes


class Car : public Vehicle, public FourWheeler {
};

// main function
int main()
{
    // Creating object of sub class will
    // invoke the constructor of base classes.
    Car obj;
    return 0;
}
Multiple Inheritance : Example Code 2
Multiple Inheritance : Example Code 2 cont...
Ambiguity in Multiple 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.

getUniversityDetails() getUniversityDetails()

?
How to Resolve Ambiguity

We can solve using scope resolution operator


Syntax:
ObjectName.ClassName::FunctionName();
Diamond Problem in Multiple Inheritance
• The diamond problem occurs when two super classes of a class have a common
base class. 

In the following diagram, the TA class gets two


copies of all attributes of Person class, this
causes ambiguities.
Diamond Problem by Example

Constructor of ‘Person’ is called two


times. So, object ‘ta1’ has two copies of
all members of ‘Person’, this causes
ambiguities. 
Diamond Problem Solution
• The solution to this problem is ‘virtual’ keyword. Make classes ‘Faculty’ and ‘Student’ as virtual base
classes to avoid two copies of ‘Person’ in ‘TA’ class.
• A single copy of its data members is shared by all the base classes that use virtual base.
Types of Inheritance
3. Multilevel Inheritance: In this type of inheritance, a derived class is created from
another derived class.
Multilevel inheritance Example:

One class is going to become base class for other derived class
PMFund Base Class for class Bank
FundAmount=1000

Bank Derived Class from PMFund and


Base Class for Customer
BankName=“SBI”
IFSCCode=“SBI001”

Customer Derived Class from Bank


Cust_Name,
Cust_Id,
BalanceAmount
checkBalance():
Multilevel Inheritance : Example Code
#include <iostream>
using namespace std; // main function
// base class int main()
class Vehicle { {
public:     // Creating object of sub class will
    Vehicle() { cout << "This is a Vehicle\n"; }     // invoke the constructor of base
}; // classes.
    Car obj;
    return 0;
// first sub_class derived from class vehicle }
class fourWheeler : public Vehicle {
public:
    fourWheeler()
    {
        cout << "Objects with 4 wheels are vehicles\n";
    }
};

// sub class derived from the derived base class fourWheeler


class Car : public fourWheeler {
public:
    Car() { cout << "Car has 4 Wheels\n"; }
};
Types of Inheritance
4. Hierarchical Inheritance: In this type of inheritance, more than one subclass is
inherited from a single base class. i.e., more than one derived class is created from a
single base class.
Hierarchical inheritance Example

Bank
Credit()
Debit()

Axis Bank HDFC Bank ICICI Bank


Loan_criteria() Loan_criteria() Loan_criteria()
RateofInterest() RateofInterest() RateofInterest()
Hierarchical Inheritance : Example Code
#include <iostream> // main function
using namespace std; int main()
// base class {
class Vehicle {     // Creating object of sub class will
public:     // invoke the constructor of base class.
    Vehicle()     Car obj1;
{ cout << "This is a Vehicle\n"; }     Bus obj2;
};     return 0;
}

// first sub class


class Car : public Vehicle {
};

// second sub class


class Bus : public Vehicle {
};
Types of Inheritance
5. Hybrid (Virtual) Inheritance: Hybrid Inheritance is implemented by combining
more than one type of inheritance. For example: Combining Multilevel inheritance and
Multiple Inheritance as shown below. 

Example:
Multiple
Inheritance
Hybrid Inheritance : Example Code

Vehicle Fare

Car Bus
Type Conversion
Type Conversion
• Basic data types conversion done automatic by compiler
• User define data type conversion not done automatically
• User define data type conversion done by using either constructor or
by using casting operator

Three type of situation occur during user define type conversion:


• 1. basic type to class type(using constructor)
• 2. class type to basic type(using casting operator function)
• 3. class type to class type (using constructor and casting operator
function both)
What will be output?
#include <iostream>
using namespace std; A) 2110
int main() B) 1210
{
double a = 21.09399;
C) 21
float b = 10.20f; D) 121
int c ;
c = a;
cout << c ;
c = b;
cout << c ;
return 0;
}
1. Basic type to Class type (using Constructor)
• Conversion of primitive data type (basic type) to user-defined type (class type): The idea is to
use the constructor to perform type conversion during the object creation.
#include <iostream>
using namespace std;
class A
{
Basic type to class type achieved by using
constructor.
};
int main()
{
A a1;
int x=8;
a1=x ;//basic to class type
return 0;
}
Example Basic to Class : Using Constructor
• Program below converts time in minutes (integer) to time in hours and minutes (Time class)
#include <iostream> void Time :: Display()
using namespace std; {
// Time Class    cout << “Time = ”<< hour << “ hrs and ”;
class Time {    cout << mins << “ mins \n”;
    int hour; }
    int mins;
public:
    // Default Constructor int main()
    Time() {
    {     // Object of Time class
        hour = 0;     Time T1;
        mins = 0;     int dur = 95;
    }  
    // Parameterized Constructor     // Conversion of int type to class type
    Time(int t)     T1 = dur;
    {     T1.Display();
        hour = t / 60;  
        mins = t % 60;     return 0;
    } }
    // Display time in hrs and mins
    void Display();
 };
Time
hours, mins

display()
2. Class type to Basic type (using Casting Operator)
• Conversion of class object to primitive data type: In this conversion, the from type
is a class object and the to type is primitive data type. The normal form of an 
overloaded casting operator function, also known as a conversion function. Below is
the syntax for the same:

This function converts a user-defined data type to a primitive data type. For
Example, the operator double() converts a class object to type double, the
operator int() converts a class type object to type int, and so on. 
class type to basic type(using casting operator
function)
Class type to basic type done by using casting operator function
1.It must be a define inside in class.
2.It must not specify a return type in function signature.
3.It must not have any arguments.
class A
{};
A a1;
int x;
x=a1 //class type to basic type
casting operator function
Syntax:
operator dest_typename()
{ operator int()
return statement; {
} return a;
}
Example Class to Basic : Using Casting Operator
• Program below converts time class to time
Example Cont...
3. Class type to Class type
Conversion of class type to another class type: In this type, one class type is converted
into another class type. It can be done  in 2 ways :
1. Using Constructor
2. Using Overloading Casting Operator
First approach : Using Constructor:-
Left side of assignment operator(=) which is class object we have to
create constructor in that class here in Class A. i.e.,
In the Destination class we use the constructor method.
Example Class to Class : Using Constructor in Destination
• Program below converts units from CGS class to FPS class
class CGS
 {
     int mts; //meters
     int cms; //centimeters
     public:
       void showdata()
   {
       cout<<"Meters and centimeters in CGS system:";
       cout << mts<<" meters "<<cms<<" centimeters" <<endl;
   }
   CGS(int x,int y) // parameterized constructor
   {
       mts=x;
     cms=y;
   }
    int getcms()
   {
       return cms;
   }
   int  getmts()
   {
       return mts;
   }
 };
Example cont...
class FPS
 {
   int feet;
   int inches;
   public:
   FPS() // default constructor
   {
int main()
       feet=0;
 {
       inches=0;
     CGS d1(9,10);
   }  
     FPS d2;
  FPS(CGS d2)
     d2=d1;
   {
//to display CGS values
       int x;
     d1.showdata();
       x=d2.getcms()+d2.getmts()*100;
//to display FPS values
       x=x/2.5;
     d2.showdata();
       feet=x/12;
     return 0;
       inches=x%12;
 }
    }
   void showdata()
   {
       cout<<"feet and inches in FPS system:";
       cout << feet<<" feet "<<inches<<" inches" << endl;
   }
 };
3. Class type to Class type
Second approach using overloaded casting operator function:
Right side of assignment operator(=) which is class object, we have to
create casting operator function in that class here class B i.e.,
Here we use Overloading casting operator in source class

objectY is the source class object, objectX is the destination class object,
• To convert objectY into objectX, let us define casting operator in source
class.
Example Class to Class : Using Casting Operator in Source
• Program below converts time in hours and minutes to time in minutes.
• In this example, minute class is destination class and time class is source class.
• So, we need to overload the destination class in the source class
• Here, we should not tell the return type, but we returns the overloaded class object  i.e.
returning value without specifying return type
class Minute {

public:
   int mins;
    // Constructors
    Minute()
    {
        mins = 0;
    }
    // Function to print the value of minutes

    void show()
    {
        cout << "\nTotal Minute : " << mins << endl;
    }
};
Example cont...
class Time {
    int hr, mins;
public:
    // Parameterized Constructor
    Time(int h, int m)
    { int main()
        hr = h; {
        mins = m;     Time T1(3,40);
    }     Minute m;
    operator Minute () //overloading minute class     m=T1;
    { //minute class is destination
        Minute m; //Time class is source class
        m.mins = (hr * 60) + mins;     T1.show();
        return m;     m.show();
    }     return 0;
    // Function to print the value of }
    // hours and minutes
    void show()
    {
        cout << "Hour: " << hr << endl;
        cout << "Minute : " << mins << endl;
    }
};

You might also like