Friday, 1 November 2024

OOPS c++ Inheritance MSBTE III Sem

Unit 3

 Summer 22

Q1> Describe visibility modes and their effects used in inheritance ? 

Ans:  In C++, visibility modes (or access specifiers) in inheritance control how the members of a base class are accessible to derived classes and outside code. The three main visibility modes are:

·        Public: When the member is declared as public, it is accessible to all the functions of the program.

·        Private: When the member is declared as private, it is accessible within the class only.

·        Protected: When the member is declared as protected, it is accessible within its own class as well as the class immediately derived from it.

Visibility of Inherited Members

Base class visibility

Derived class visibility

Public

Private

Protected

Private

Not Inherited

Not Inherited

Not Inherited

Protected

Protected

Private

Protected

Public

Public

Private

Protected


Q2> Describe the concept of virtual base class with example

Ans: Virtual base classes are used in virtual inheritance in a way of preventing multiple “instances” of a given class appearing in an inheritance hierarchy when using multiple inheritances.  

Need for Virtual Base Classes: Consider the situation where we have one class A . This class A is inherited by two other classes B and C. Both these class are inherited into another in a new class D as shown in figure below. 

As we can see from the figure that data members/function of class A are inherited twice to class D. One through class B and second through class C. When any data / function member of class A is accessed by an object of class D, ambiguity arises as to which data/function member would be called? One inherited through B or the other inherited through C. This confuses compiler and it displays error. 


Q3> Write a c++ program to implement following inheritance. Accept and display total of one object of result:

Ans:

 

 


#include <iostream> 

using namespace std; 

class Science

{

public:

    int varPhysicsMrks ;

    int varChemMrks;

void getMarks (int Phy, int Chem)

{

 varPhysicsMrks = Phy;

 varChemMrks = Chem;

}

};

 

class Maths

{

    public:

    int varAlezbraMrks;

    int varGeometryMrks;

    void getGeoMarks (int Alz, int Geo)

    {

     varAlezbraMrks = Alz;

     varGeometryMrks = Geo;

    }

};

 

class Result: public Science, public Maths

{

public:

    int varResult;

    void DisplayResult()

    {

        varResult = varPhysicsMrks + varChemMrks + varAlezbraMrks + varGeometryMrks;

        std::cout << "Total result " << varResult << std::endl;

    }

};

 

int main()

{

    Result objResult;

    objResult.getMarks(80,56);

    objResult.getGeoMarks(50,67);

    objResult.DisplayResult();

    return 0;

}

Q4> Write a program to implement inheritance as shown in figure. Assume suitable member function. Accept and display data of one Teacher and one Officer.

Ans: 


#include <iostream> 

using namespace std; 

class Staff

{

public:

string EmpName ;

string Code;

 

void getStaff (string varEmpName , string varcode)

{

    EmpName  = varEmpName ;

    Code = varcode;

    cout<< "Employee Name = "<< EmpName << std::endl ;

    cout<< "Code = "<< Code<< std::endl;

}

};

 

class Teacher:public Staff

{

    public:

    string Subject;

    void getSubjectCode (string varSubject)

    {

     cout<<"Subject Code = "<<varSubject << std::endl;

    }

};

 

class Officer:public Staff

{

public:

    string varGrade;

    void DisplayGrade(string grade)

    {

        varGrade = grade;

        cout<<"Grade = "<< varGrade << std::endl;

    }

};

 

int main()

{

    Teacher objTeacher;

    Officer objOfficer;

    objTeacher.getStaff(" Ganesh Tambe ", "Computer ");

    objTeacher.getSubjectCode ("OOPS");

    objTeacher.getStaff(" Rajesh Karade", "Computer ");

    objOfficer.DisplayGrade("Manager");

    return 0;

}

Q5> Develop a C++ program for multilevel inheritance.

Multilevel inheritance is a process of deriving a class from another derived class.


When one class inherits another class which is further inherited by another class, it is known as multilevel inheritance in C++. Inheritance is transitive so the last derived class acquires all the members of all its base classes.

1st Example

#include <iostream>  

using namespace std;  

 class Animal {  

   public:  

 void eat() {   

    cout<<"Eating..."<<endl;   

 }    

   };  

   class Dog: public Animal   

   {    

       public:  

     void bark(){  

    cout<<"Barking..."<<endl;   

     }    

   };   

   class BabyDog: public Dog   

   {    

       public:  

     void weep() {  

    cout<<"Weeping...";   

     }    

   };   

int main(void) {  

    BabyDog d1;  

    d1.eat();  

    d1.bark();  

     d1.weep();  

     return 0;  

}  

 

2nd example

#include <iostream>

#include <string>

using namespace std;

 

class Person {

protected:

    string name;

    int age;

public:

    // Constructor

    Person(string n, int a) : name(n), age(a) {}

 

    // Function to display person details

    void displayPerson() {

        cout << "Name: " << name << ", Age: " << age << endl;

    }

};

class Student : public Person {

protected:

    string studentID;


public:

    // Constructor

    Student(string n, int a, string id) : Person(n, a), studentID(id) {}

    // Function to display student details

    void displayStudent() {

        displayPerson(); // Call base class function

        cout << "Student ID: " << studentID << endl;

    }

};


class GraduateStudent : public Student {

private:

    string thesisTitle;

public:

    // Constructor

    GraduateStudent(string n, int a, string id, string thesis)

        : Student(n, a, id), thesisTitle(thesis) {}


    // Function to display graduate student details

    void displayGraduateStudent() {

        displayStudent(); // Call derived class function

        cout << "Thesis Title: " << thesisTitle << endl;

    }

};

int main() {

    GraduateStudent gradStudent("Samiksha", 24, "S12345", "AI in Healthcare");

 

    // Display all details

    gradStudent.displayGraduateStudent();

    return 0;

}

3 rd Example

#include <iostream>

using namespace std;

// Base class

class Shape {

public:

    void setLength(int l) {

        length = l;

    }

    void setWidth(int w) {

        width = w;

    }

protected:

    int length, width;

};

// Derived class (inherits from Shape)

class Rectangle : public Shape {

public:

    int getArea() {

        return length * width;

    }

};

// Derived class (inherits from Rectangle)

class Box : public Rectangle {

public:

    void setHeight(int h) {

        height = h;

    }

    int getVolume() {

        return length * width * height;

    }

private:

    int height;

};

int main() {

    // Create an object of the derived class Box

    Box myBox;

    // Set dimensions

    myBox.setLength(5);

    myBox.setWidth(4);

    myBox.setHeight(3);

    // Calculate and display area and volume

    cout << "Area of the rectangle: " << myBox.getArea() << endl;

    cout << "Volume of the box: " << myBox.getVolume() << endl;

    return 0;

}


Q6> Develop a C++ program to implement inheritance shown in following figure

#include <iostream>

#include <conio.h>

using namespace std;

 

class HOD {

protected:

    char HODName[10];

    char deptName[20];

};

 

class Faculty : public HOD {

    char facultyName[10];

public:

    void getfaculty() {

        cout << "Enter department name: "<< endl;

        cin >> deptName;

        cout << "Enter HOD name: "<< endl;

        cin >> HODName;

        cout << "Enter Faculty name: "<< endl;

        cin >> facultyName;

    }

    void putfaculty() {

        cout << "\nDepartment name: " << deptName << endl;

        cout << "HOD name: " << HODName << endl;

        cout << "Faculty name: " << facultyName << endl;

    }

};

 

class LabIncharge : public HOD {

protected:

    char labinchName[10];

};

 

class Technical : public LabIncharge {

    char qual[10];

public:

    void getlabT() {

        cout << "Enter department name: "<< endl;

        cin >> deptName;

        cout << "Enter HOD name: " << endl;

        cin >> HODName;

        cout << "Enter Lab Incharge HODname: " << endl;

        cin >> labinchName;

        cout << "Enter Qualification: "<< endl;

        cin >> qual;

    }

    void putlabT() {

        cout << "\nDepartment name: " << deptName << endl;

        cout << "HOD name: " << HODName << endl;

        cout << "Lab Incharge name: " << labinchName << endl;

        cout << "Qualification: " << qual << endl;

    }

};

 

class Student : public HOD {

    char studname[10];

public:

    void getstudent() {

        cout << "Enter department name: "<< endl;

        cin >> deptName;

        cout << "Enter HOD name: "<< endl;

        cin >> HODName;

        cout << "Enter Student name: "<< endl;

        cin >> studname;

    }

    void putstudent() {

        cout << "\nDepartment name: " << deptName << endl;

        cout << "HOD name: " << HODName << endl;

        cout << "Student name: " << studname << endl;

    }

};

 

int main() {

    Faculty f;

    Student s;

    Technical t;

   

    f.getfaculty();

    s.getstudent();

    t.getlabT();

   

    f.putfaculty();

    s.putstudent();

    t.putlabT();

    return 0;

}

Q7> Give the syntax for constructor in derived classes.

In C++, when creating a derived class that inherits from a base class, you can use a constructor in the derived class to initialize both its own members and those of the base class. Here's the syntax for defining a constructor in a derived class:

class Base {

public:

    Base(int value) {

        // Base class constructor implementation

    }

};

 

class Derived : public Base {

public:

    // Constructor of the derived class

    Derived(int value1, int value2) : Base(value1) {

        // Derived class constructor implementation

        // value2 can be used to initialize members specific to Derived

    }

};

 

Q8> Write a program on single inheritance.

Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class.



Where 'A' is the base class, and 'B' is the derived class.

#include <iostream>  

using namespace std;  

class A  

{  

    int a = 4;  

    int b = 5;  

    public:  

    int mul()  

    {  

        int c = a*b;  

        return c;  

    }     

};  

  

class B : private A  

{  

    public:  

    void display()  

    {  

        int result = mul();  

        cout <<"Multiplication of a and b is : "<<result<< endl;  

    }  

};  

int main()  

{  

   B b;  

   b.display();  

  

    return 0;  

}  

 

Q9> Write a program on hybrid inheritance.

Ans: Hybrid Inheritance Hybrid inheritance is a combination of more than one type of inheritance.

Let's see a simple example:

#i     



#include <iostream>  

using namespace std;  

class A  

{  

    protected:  

    int a;  

    public:  

    void get_a()  

    {  

       cout << "Enter the value of a: " << endl;  

       cin>>a;  

    }  

};  

  

class B : public A   

{  

    protected:  

    int b;  

    public:  

    void get_b()  

    {  

        cout << "Enter the value of 'b' : " <<  endl;  

        cin>>b;  

    }  

};  

class C   

{  

    protected:  

    int c;  

    public:  

    void get_c()  

    {  

        cout << "Enter the value of c is : " << endl;  

        cin>>c;  

    }  

};  

  

class D : public B, public C  

{  

    protected:  

    int d;  

    public:  

    void mul()  

    {  

         get_a();  

         get_b();  

         get_c();  

         cout << "Multiplication of a,b,c is : " <<a*b*c<< endl;  

    }  

};  

int main()  

{  

    D d;  

    d.mul();  

    return 0;  

}  

Output:

Enter the value of 'a' :

10

Enter the value of 'b' :

20

Enter the value of c is :

30

Multiplication of a,b,c is : 6000

 

Q10> What is inheritance? Give different types of inheritance.

Inheritance

In C++, inheritance is a process in which one object acquires all the properties and behaviours of its parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviours which are defined in other class.

In C++, the class which inherits the members of another class is called derived class and the class whose members are inherited is called base class. The derived class is the specialized class for the base class.

Derived Classes

A Derived class is defined as the class derived from the base class.

The Syntax of Derived class:

1.    class derived_class_name : visibility-mode base_class_name  

2.    {  

3.        // body of the derived class.  

4.    }  

 

Where,

derived_class_name: It is the name of the derived class.

visibility mode: The visibility mode specifies whether the features of the base class are publicly inherited or privately inherited. It can be public or private.

base_class_name: It is the name of the base class.

·        When the base class is privately inherited by the derived class, public members of the base class becomes the private members of the derived class. Therefore, the public members of the base class are not accessible by the objects of the derived class only by the member functions of the derived class.

·        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 base class.

·        Single inheritance - Single inheritance is defined as the inheritance in which a derived class is inherited from the only one base class.

·        Multiple inheritance - Multiple inheritance is the process of deriving a new class that inherits the attributes from two or more classes.

·   Hierarchical inheritance - Hierarchical inheritance is defined as the process of deriving more than one class from a base class.

·        Multilevel inheritance - Multilevel inheritance is a process of deriving a class from another derived class.

·        Hybrid inheritance - Hybrid Inheritance Hybrid inheritance is a combination of more than one type of inheritance.

 

Q11> Explain multilevel inheritance with an example.

Ans : Multilevel inheritance is a type of inheritance in C++ where a class is derived from another derived class. In other words, a class serves as a base class for another class, which in turn acts as a base class for a further derived class. It forms a hierarchy of classes.

#include <iostream>

using namespace std;

// Base class

class Vehicle {

public:

    Vehicle() {

        cout << "Vehicle constructor called." << endl;

    }

    void start() {

        cout << "Vehicle started." << endl;

    }

};

// Derived class from Vehicle

class Car : public Vehicle {

public:

    Car() {

        cout << "Car constructor called." << endl;

    }

    void accelerate() {

        cout << "Car is accelerating." << endl;

    }

};

// Further derived class from Car

class SportsCar : public Car {

public:

    SportsCar() {

        cout << "SportsCar constructor called." << endl;

    }

    void turboBoost() {

        cout << "SportsCar turbo boost activated!" << endl;

    }

};

int main() {

    SportsCar myCar;

    myCar.start();         // Inherited from Vehicle

    myCar.accelerate();    // Inherited from Car

    myCar.turboBoost();    // SportsCar's own method

    return 0;

}

Output :

Vehicle constructor called.

Car constructor called.

SportsCar constructor called.

Vehicle started.

Car is accelerating.

SportsCar turbo boost activated!

Explanation:

1.    Vehicle: The base class with a constructor and a method start().

2.    Car: Derived from Vehicle. It inherits the start() method and defines its own accelerate() method.

3.    SportsCar: Derived from Car. It inherits both the start() and accelerate() methods and defines its own turboBoost() method.

When we create an object of SportsCar, the constructors are called in the order of inheritance: Vehicle → Car → SportsCar. This demonstrates how functionality is passed down through multiple levels of inheritance.

 

Q12> Write a C++ program to implement multiple inheritance as shown in following figure. Accept and display data of test marks and sport’s marks using object of class ‘result’.


#include <iostream>

using namespace std;

// Base class to store student information

class Student {

protected:

    string name;

    int rollNo;

 

public:

    void inputStudentDetails() {

        cout << "Enter student name: ";

        cin >> name;

        cout << "Enter roll number: ";

        cin >> rollNo;

    }

    void displayStudentDetails() {

        cout << "Student Name: " << name << endl;

        cout << "Roll Number: " << rollNo << endl;

    }

};

// Class to handle test marks (derived from Student)

class Test : public Student {

protected:

    float testMarks;

public:

    void inputTestMarks() {

        cout << "Enter test marks (out of 100): ";

        cin >> testMarks;

    }

 

    void displayTestMarks() {

        cout << "Test Marks: " << testMarks << "/100" << endl;

    }

};

// Class to handle sports marks

class Sports {

protected:

    float sportsMarks;

public:

    void inputSportsMarks() {

        cout << "Enter sports marks (out of 50): ";

        cin >> sportsMarks;

    }

    void displaySportsMarks() {

        cout << "Sports Marks: " << sportsMarks << "/50" << endl;

    }

};

// Derived class from both Test and Sports

class Result : public Test, public Sports {

public:

    void displayResult() {

        displayStudentDetails();

        displayTestMarks();

        displaySportsMarks();

        float total = testMarks + sportsMarks;

        cout << "Total Marks: " << total << "/150" << endl;

    }

};

int main() {

    Result studentResult; //Object Declaration

    // Accepting data

    studentResult.inputStudentDetails();

    studentResult.inputTestMarks();

    studentResult.inputSportsMarks();

 

    // Displaying data

    cout << "\n--- Result ---\n";

    studentResult.displayResult();

    return 0;

}

Output Example :

Enter student name: John

Enter roll number: 123

Enter test marks (out of 100): 85

Enter sports marks (out of 50): 40

 

--- Result ---

Student Name: Arpit

Roll Number: 123

Test Marks: 85/100

Sports Marks: 40/50

Total Marks: 125/150

Q13 > List different types of inheritance.

Refer question 10

Q14> Write a C++ program to implement inheritance as shown in figure:


#include <iostream>

using namespace std;

// Base class Teacher

class Teacher

{

public:

    string Name;

    int emp_id;

void setTeacherDetails()

{

    cout<<"Enter Employee Name:"<< endl;

    cin>>Name;

    cout<<"Enter Employee ID:"<< endl;

    cin>>emp_id;

}

void displayTeacherDetails()

{

    cout << "Employee Name:" << Name << endl;

    cout << "Employee ID: "<< emp_id << endl;

}

};

// Base class Student

class Student

{

    public:

    string S_Name;

    int Roll_No;

    void setStudentDetails()

    {

        cout<<"Enter Student Name:"<< endl;

        cin>>S_Name;

        cout<<"Enter Roll Number ID:"<< endl;

        cin>>Roll_No;

    }

    void displayStudentDetails()

    {

        cout << "Stúdent Name: " << S_Name << endl;

        cout << "Roll Number: " << Roll_No << endl;

    }

};

      // Derived class Info inheriting from both Teacher and Student class Info: public Teacher, public Student

    class Info:public Teacher,public Student

    {

    public:

        void displayInfo()

        {

            displayTeacherDetails();

            displayStudentDetails();

        }

    };

int main()

{

    Info onjinfo;

    onjinfo.setTeacherDetails();

    onjinfo.setStudentDetails();

    cout<<endl;

    onjinfo.displayInfo();

}

Q15>Write program on Hybrid Inheritance

Ans:

C++ Program

#include <iostream>

using namespace std;

// Base class

class Person {

protected:

    string name;

public:

    void getName() {

        cout << "Enter name: ";

        cin >> name;

    }

    void showName() const {

        cout << "Name: " << name << endl;

    }

};

// Intermediate base class

class Employee : public Person {

protected:

    int employeeID;

public:

    void getEmployeeID() {

        cout << "Enter employee ID: ";

        cin >> employeeID;

    }

    void showEmployeeID() const {

        cout << "Employee ID: " << employeeID << endl;

    }

};

 

// Another intermediate base class

class Student : public Person {

protected:

    int studentID;

public:

    void getStudentID() {

        cout << "Enter student ID: ";

        cin >> studentID;

    }

    void showStudentID() const {

        cout << "Student ID: " << studentID << endl;

    }

};

// Derived class

class WorkingStudent : public Employee, public Student {

public:

    void getInfo() {

        // From Employee

        Employee::getName();  // Resolves ambiguity for 'name' from Person via Employee

        getEmployeeID();

        // From Student

        Student::getName();  // Resolves ambiguity for 'name' from Person via Student

        getStudentID();

    }

    void showInfo() const {

        // From Employee

        Employee::showName();

        showEmployeeID();

        // From Student

        Student::showName();

        showStudentID();

    }

};

int main() {

    WorkingStudent ws;

    cout << "Enter details for Working Student:" << endl;

    ws.getInfo();

    cout << "\nDetails of Working Student:" << endl;

    ws.showInfo();

    return 0;

}

Explanation:

1.    Base Class (Person):

o   Contains name as a common attribute.

2.    Intermediate Base Classes (Employee and Student):

o   Employee inherits name from Person and adds employeeID.

o   Student also inherits name from Person and adds studentID.

3.    Derived Class (WorkingStudent):

o   Inherits from both Employee and Student.

o   Since WorkingStudent inherits name from two paths (Employee and Student), we resolve this ambiguity using the scope resolution (Employee::getName() and Student::getName()).

 



No comments:

Post a Comment

Summer 2018 Programming in C Solved Question Paper

Summer 2018 Semester II – C Programming   Q1. Attempt any FIVE of the following : 10 (a) Define : (i) Two dimensional array In C...