68
Prof.Manoj S.Kavedia (9860174297)([email protected]) Inheritance Q1.What is inheritance state its purpose ? Ans. The mechanism of deriving a new class from an old class is called inheritance. Inheritance provides the concept of reusability. The C++ classes can be reused using inheritance. In C++, the classes can be reused in several ways. The already written, tested class can be reused by using properties of the existing ones. This is achieved by creating new classes from the existing one. This mechanism is known as Inheritance. The old class is referred as Base, Super or parent class whereas the new class is called as derived , child or sub class. Features or Advantages of Inheritance 1. Reusability Inheritance helps the code to be reused in many situations. The base class is defined and once it is compiled, it need not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed. 2. Saves Time and Effort The above concept of reusability achieved by inheritance saves the programmer time and effort. Since the main code written can be reused in various situations as needed. 3. Increases Program Structure which results in greater reliability. 4. Polymorphism Q2.What is not inherited from the base class? Ans. In principle, a derived class inherits every member of a base class except: its constructor and its destructor its operator=() members its friends 4 4 Inheritance Syllabus Concepts of inheritance, Derived classes, Member declaration (Protected), Types of inheritance (Single, multilevel, multiple, hierarchical, Hybrid inheritance), Virtual base classes, Abstract classes, Constructors in derived classes, Member classes. 1

Chapter 4 Inheritance

Embed Size (px)

DESCRIPTION

Inheritance

Citation preview

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Inheritance

    Q1.What is inheritance state its purpose ?Ans. The mechanism of deriving a new class from an old class is called inheritance. Inheritance provides the concept of reusability. The C++ classes can be reused using inheritance.

    In C++, the classes can be reused in several ways. The already written, tested class can be reused by using properties of the existing ones. This is achieved by creating new classes from the existing one. This mechanism is known as Inheritance.

    The old class is referred as Base, Super or parent class whereas the new class is called as derived , child or sub class.

    Features or Advantages of Inheritance 1. Reusability

    Inheritance helps the code to be reused in many situations. The base class is defined and once it is compiled, it need not be reworked. Using the concept of inheritance, the programmer can create as many derived classes from the base class as needed while adding specific features to each derived class as needed.

    2. Saves Time and Effort The above concept of reusability achieved by inheritance saves the programmer

    time and effort. Since the main code written can be reused in various situations as needed.

    3. Increases Program Structure which results in greater reliability.4. Polymorphism

    Q2.What is not inherited from the base class?Ans. In principle, a derived class inherits every member of a base class except:

    its constructor and its destructor its operator=() members its friends

    44 InheritanceSyllabusConcepts of inheritance, Derived classes, Member declaration (Protected), Types of inheritance (Single, multilevel, multiple, hierarchical, Hybrid inheritance), Virtual base classes, Abstract classes, Constructors in derived classes, Member classes.

    1

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Although the constructors and destructors of the base class are not inherited themselves, its default constructor (i.e., its constructor with no parameters) and its destructor are always called when a new object of a derived class is created or destroyed.

    If the base class has no default constructor or you want that an overloaded constructor is called when a new derived object is created, you can specify it in each constructor definition of the derived class:

    Q3. State the characteristic of inheritanceAns. The Characteristics of Inheritance are as follows

    a. The derived class inherits some or all of the properties of the base class.b. A derived class with only one base class is called single inheritance.c. A private member of a class cannot be inherited either in public mode or in

    private mode.d. A protected member inherited in public mode becomes protected, whereas

    inherited in private mode becomes private in the derived class.e. A public member inherited in public mode becomes public whereas inherited in

    private mode becomes private in the derived class.

    Types of Inheritance

    Q4.List and describe different types of inheritanceAns. There are different of inheritance;

    1) Single inheritance ( One base class)2) Multilevel inheritance ( derived from derived class )3) Hierarchical inheritance ( one base class and many derived class )4) Multiple inheritance ( Many super classes )5) Hybrid inheritance

    2

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Q5.Describe how derive a class from base classAns. Derived class is defined by specifying a relationship to base class in addition to its own details. The general format is,

    Class derived name: visibility_mode base class{ ------------- };

    The colon indicates that the derived class inherits the properties of base class. Visibility mode is optional if pre4sent may be private or public. But by default it is private.

    Example : class B is the base class. Class d1 is derived from B privately while class d2 is derived from publicly.

    Class B{

    };class d1: private B

    {}; //Ist case

    class d2:public B{

    }; //IInd case

    Condition case 1When base class is privately inherited by a derived class. The public member of

    base class becomes the private members of derived class & therefore the public members of base class can be accessed by the member function of derived class. But a public members of class be accessed by its own object by using dot operator(.).

    Condition case 2On the other hand when base class is publicly inherited the public members of

    derived class. & therefore they are accessible to the object of derived class. Class B{

    int x;public:

    int y;};

    class d1: private B{

    int p;public:

    int q;};

    class d2:public B{

    int c;

    B

    Class D2

    Private :int c ;

    Public :int d ;int y ;

    Publically Inherited

    B

    Class D1

    Private : int p; int y;

    Public :int q ;void disp();

    Privately Inherited

    3

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    public:int d;

    };

    In both the cases the private members of base class are not inherited that is the data members of class B is never inherited. But adding the properties of inherited class inherited when used to modify & extend the capabilities of existing class becomes the powerful growth of program development.

    Single Inheritance

    Q6.Describe Single inheritance with exampleAns. Single InheritanceThe derived class from one base class is called as single inheritance as shown in figure.

    //Base class

    //derived classSyntax:

    Class A { . . . . . . };

    Class B: private/public A{ ------- };

    Consider the example of single inheritance as shown in above figure. The class A is the base class while class B is the derived class. Class A contains one private member and one public data member and one public data member with three member functions. Class B contains one private data member and two public member functions.

    Class B is publicly inherited from class A. Therefore class B has all the public members of class A in the public section of class B. The private members of class A cannot be inherited in effect class B and has one public data member and five member functions along with one private data member.

    Class A{

    int a;public:

    int b;void getd();void disp();int geta(){

    return (a)}

    };

    A

    B

    4

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    class B: public A{

    int C;public:

    void input();void output();

    };

    Q7.Demonstrate single Inheritance with exampleAns.

    /* Program to illustrates Single Inheritance -Public */#include # include /*----------------------Class Design-------------------------*/class A{

    int n1; // private data memberpublic :

    int n2; // public data membervoid read_n1(int); // public member functionsvoid display_n1n2();

    };// B as an extension of A

    class B : public A // public derivation{

    int b; // private data memberpublic :

    void read_n2_and_b(int, int);// public member functionsvoid display_b();

    };

    /*----------------------Class Implementations---------------------*/

    // member function definitions for class Avoid A::read_a1(int x){

    n1 = x;}void A::display_n1n2(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    n2 = x; // accessing public data member of base directlyb = y;

    }void B::display_b(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    val=a;}

    };

    class Cube: public Value {

    public: int cube()

    { return (val*val*val);

    } };int main () {

    Cube cub; cub.set_values (5); cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    void B :: get ab(void){

    a= 5; b= 10;}

    int B :: get_a(){

    return a;}

    void B :: show_a(){

    Cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Ans. Singe private inheritance # include#include Class B

    {int a;

    public:int b;void get_ab( ); int get_a(void); void show_a (void);

    };

    class D : private B{

    int c;public:

    void mul (void); void dispiay(void);

    };

    void B :: get ab(void){

    Couta>>b;

    } int B :: get_a()

    {return a;

    }void B :: show_a()

    {Cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    D d;

    d.mul(); d.display();

    // d.b = 20; // Wont work because b has became privated.mul();d.disp1ay();return 0;

    }

    Q12.Describe how private members are inheritedAns.Private members of base class cant be inherited. Therefore class cant achieve the properties of private data members. If we have to derive private members we have to make it accessible to all other functions. Thus eliminating the advantage of data hiding concept.

    C++ provides another visibility modifiers that are protected. Which saves unlimited purpose in inheritance. A member declared as protected is accessible by the member function within its class and any class immediately derived from it. It cant be accessed by the function outside these two classes. A class can have all the visibility modes shown below.

    Class ABC{

    private: //visibility within class------------------------------------------

    Protected: //visibility within class & immediate derived class.------------------------------------------

    Public: //Visible in function program------------------------------------------

    };When a protected member is inherited in public mode. It becomes protected in

    derived class & accessible by the member function of the derived class. It is also ready for further inheritance. Protected members inherited in the private mode become the private data members in the derived class. It is available for the member function of class but not inherited for further inheritance.

    Base class visibility

    Derived classPrivately Inheritance Publicly Inherited

    Private Non inherited Not inheritedProtected Private ProtectedPublic Private Public

    10

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Q13.Describe how protected member can be declaredAns. The protected members are declared similar to other members like public or private with the only difference that it is to be preceded by the keyword protected.Syntax

    For data members protected:

    int rollno;

    For member functions protected:

    void getdata ();

    Q14.What are protected member? state its useAns. A member declared as protected is accessible by the member function within its class and any class immediately derived from it. It cant be accessed by the function outside these two classes.

    If you derived, the class privately, then all public members of base becomes private of derive. And if you derive it publically, then all public of base becomes public of derived as well as they becomes accessible to all other member function and also private member of a base class cannot be inherited and therefore it is not available for the derived class directly.

    So there is one more visibility modifier, known as protected is accessible by the member functions within its class and any class immediately derived from it. It cannot be accessed by the function outside these two classes.

    Note that, when a protected member is inherited in public mode, it becomes protected in the derived class too, and therefore is accessible by the member functions of the derived class.

    The following table is showing these visibility of data.

    Q15.Write a program to demonstrate inheritance using protected/Private inheritanceAns. /*Program to demonstrate Single Inheritance by PROTECTED Derivation */

    11

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    #include #include/*----------------------Declaration of Class -------------------------*/class A {

    protected :int a1; // protected data member

    public :int a2; // public data member

    void set_a1(int); // public member functionsint get_a1();

    };

    // B as an inheritance of Aclass B : private A // private derivation {

    int b; // private data memberpublic :

    void set(int, int, int); // public member functionsvoid display();

    };/*----------------------implementation of complete Class ---------------------*/

    // member function definitions for class Bvoid B::set(int x, int y, int z)

    {// accessing the protected member of the class

    a1=x;

    // accessing the public member of the classa2=y;

    // accessing own private member as usualb = z;

    }

    void B::display(){

    // accessing the protected member of the classcout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    }

    /*----------------------End of Class definitions ---------------*/void main(void) {

    B obj1;

    // Outside World Only See The Interface Of The Derived Classobj1.set(101,202,303);cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    class B : public A // public derivation {

    int b; // private data memberpublic :

    void set(int, int); // public member functionsvoid display();

    };/*----------------------implementation of complete Class ---------------------*/

    // member function definitions for class Bvoid B::set(int x, int y)

    {// accessing the protected member of the class

    a1=x;

    // accessing own private member as usualb = z;

    }

    void B::display(){

    // accessing the protected member of the classcout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    b=303

    ExplanationIn the above example two classes A and B are defined. The class A contains

    One protected date member Al and one public data member A2. Class B is derived from class A using public inheritance.

    As stated above protected member is like a private member but accessible to the derived class protected member and public data member become public when inherited in public mode. So the data members A2 of class A is accessed using object of class B and other member of class B are accesses in member function of class B.

    Method OverridingQ17.Describe method overriding with exampleAns. Method overriding is redefining the method (member function) in the derivedclass with the same name as that of public method of the base class.

    When a member function in the base class is overridden in the derived class, the object of the derived class cannot access the functions original definition from the base. It only can access the new definition implemented in the derived class.The question is, if overriding is opposite to that of inheritance then why do we use it ? The answer is simple. Inheritance can be used to reuse a class definition already available. Suppose if we want to reuse the available class but a single member function of the base is not satisfying your software requirements. That single function needs update.

    One solution is to directly modify that class and use it. Normally, every software component has the owner and only owner is supposed to modify the code. Otherscannot modify it. Another reason for not directly modifying the available class is that class might be used by some other system which requires maintaining the original function definition.

    Therefore, the second solution is applied; create a new class definition from the original by inheriting it. In the new derived -class insert a function definition for the function which you want to modify. C++ gives you this flexibility of overriding functions from the base just by redefining it with the same name in the derived class. Software reusability gets widened due to overriding. Without which we would have reimplemented the whole class again keeping all but one functions same.

    Example/* Program Overriding Member Functions */#include #include /*----------------------Class Declaration-------------------------*/class employee{

    char name[10];int empno;

    public :void set(int, char*);void display_heading();

    15

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    void display();};class manager : public employee{

    int no_of_projects;public:

    void set(int, char*, int); // functions overriding thevoid display_heading(); // base class definitions

    void display_projects();};/*----------------------Implementation of Class ---------------------*/// member function definitions for 'employee'void employee::set(int c, char* s){

    empno = c;strcpy(name, s);

    }void employee::display_heading(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    manoj.display_heading();manoj.display();manoj.display_projects();

    }

    ExplanationClass employee has three public methods. set(), display() and

    display_header(). It is a self sufficient class and can be used to generate objects.The second class manager is derived from employee using public

    inheritance. Also manager is an employee and hence need to have all the attributes of the employee class. But it also want to have one additional attribute no_of_projects it is currently handling. The inheritance is a good idea here to get the functionality of employee accessible through manager.

    The only difference are, managers information contains, name, empno and no.of_projects which forced us to override function set() which initialises its own field no_of_projects and invokes the set() function for the base class passing the remaining two parameters. Another way to the overriding. The origin functionality thus can be invoked from a new overriding definition, only thing is you explicitly need to give the base class name and the scope resolution operator; otherwise it will become the recursive call with one less parameter which leads to compilation error.

    The second function which is overridden by manager is display(). We want here to display manager details instead of a general heading for all employee. Employee information. This new definition need not invoke the original definition as we want only the new message to be printed and not the old one.

    The third base function display() is not overridden and hence get inherited to the manager class directly. Thus for the object of type manager four method are available set( ), display( ), display_header( ), display_projects( ).

    Q18.State difference between overloading an OverridingAns.

    17

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Multilevel Inheritance

    Q19.Describe Multilevel Inheritance with exampleAns.It has more than one level of derived classes as shown in figure.class A serves as base class for the derived class B which in turn serves as base class of C. class B is known as intermediate base class while class A is super class & class C is derived class. The chain of A, B, C class is known as multilevel inheritance. The declaration syntax is;

    Overloading Overriding1.Different functions have same namename in same class.

    1.Different functions have same different class.

    2.In overloading, prototypes must differ in either in number of parameters or in their data type.

    2.In overriding the prototype for function must match exactly to the one Specified in the base class

    3.They can be static or non-staticMembers of the class.

    3.They must be Non Static.

    4.Constructors cant be overrided

    5.Use concept of Inheritance

    When an overridden methods is called from within the subclass, it will always refer to the version of that method defined by the subclass. The version of the method defined by the superclass will be overridden(hided).

    Super A Base

    IntermediateB Dervied from A /

    base for C

    Child C Dervied 18

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Class A{--------------};

    class B : visibility mode A{---------------};

    Class C : visibility mode B{--------------------};

    This process can be extended to any number of levels.

    Q20.Demonstrate Multilevel inheritance with programAns. Multilevel Inheritance

    #include #include class mm { protected: int rollno; public: void get_num(int a) {

    rollno = a; }

    void put_num() {

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    } };class res : public marks

    { protected:

    float tot; public:

    void disp(void) { tot = sub1+sub2; put_num(); put_marks(); cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    char *name; public:void getdata(int b,char *n) { rollno = b; name = n; }void putdata(void) { cout< < " The Name Of Student \t: "< < name< < endl; cout< < " The Roll No. Is \t: "< < rollno< < endl; }};

    class test:public student // Derieved Class 1 { protected: float m1,m2; public: void gettest(float b,float c) { m1 = b; m2 = c; } void puttest(void) { cout< < " Marks In CP Is \t: "< < m1< < endl; cout< < " Marks In Drawing Is \t: "< < m2< < endl; } };

    class result:public test // Derieved Class 2 { protected: float total; public: void displayresult(void) { total = m1 + m2; putdata(); puttest(); cout< < " Total Of The Two \t: "< < total< < endl; } };

    void main() { clrscr();

    21

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    int x; float y,z; char n[20]; cout< < "Enter Your Name:"; cin>>n; cout< < "Enter The Roll Number:"; cin>>x; result r1; r1.getdata(x,n); cout< < "ENTER COMPUTER PROGRAMMING MARKS:"; cin>>y; cout< < "ENTER DRAWING MARKS:"; cin>>z; r1.gettest(y,z); cout< < endl< < endl< < "************ RESULT **************"< < endl; r1.displayresult(); cout< < "**********************************"< < endl; getch();

    }

    OuputEnter Your Name:LionelEnter The Roll Number:44ENTER COMPUTER PROGRAMMING MARKS:95ENTER DRAWING MARKS:90

    ************ Result **************The Name Of Student : LionelThe Roll No. Is : 44Marks In CP Is : 95Marks In Drawing Is : 90Total Of The Two : 185**********************************

    Multiple Inheritance

    Q22.Describe Multiple Inheritance with exampleAns.A class gets inherited from one or more classes are given in the figure this is known as multiple inheritance. Multiple inheritance allows to combine features several existing class for defining one new class. The syntax for derived class using multiple inheritance is as follows.

    Class B1{ };

    class B2

    B1 B2 B3

    22

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    { };class Bn { };class D : visibility mode B1, vm B2,. . . . . . . . . , vm Bn; { };

    Where visibility mode may be public or private.For Example : declare a class p derived from m & n class m has one variable & one member function class n has one private variable & one public member function where class m is privately inherited class n is public give class p representation.

    class m{

    int x;public : void getd();

    };class n

    {private: class representation of pint y;

    public:void sum(); }

    class p:private m, private n;{public:

    void disp();}

    Q23. Demonstrate Multiple inheritance with programAns. Mutliple Inheritance

    #include #includeusing namespace std;class Square { protected:

    int l;public:

    void set_values (int x) {

    l=x; }

    };class CShow

    { public:

    void show(int i); };

    void CShow::show (int i)

    D

    M

    P

    N

    PrivatePublic

    Private :Void getd();

    Public :Void sum();Void disp();

    23

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    { cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    };

    class P:public M,public N { public: void display(void); };

    void M::get_m(int x) { m=x; }void N::get_n(int y) { n=y; }

    void P::display(void) { cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    coutroll;coutname;cout>sub3;

    }void output(){

    putdata();cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    marks m1[25];int ch;int count=0;do {

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    class IF : visibility mode Engg{ --------};

    Q27.Demonstrate Hierarchical inheritance with programAns. Hierarchical inheritance

    #include #include class Side {

    protected: int l;

    public: void set_values (int x)

    { l=x;

    } };class Square: public Side {

    public: int sq()

    { return (l *l);

    } };class Cube:public Side {

    public: int cub()

    { return (l *l*l);

    } };int main () { Square s; s.set_values (10); cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    In the above example the two derived classes "Square", "Cube" uses a single base class "Side". Thus two classes are inherited from a single class. This is the hierarchical inheritance OOP's concept in C++.

    Q28.Program to demonstrate Hierarchical inheritanceAns. Hierarchical inheritance Program#include#includeconst int len = 20 ;class student // Base class { private: char F_name[len] , L_name[len] ; int age, int roll_no ; public: void Enter_data(void) { cout > F_name ; cout > L_name ; cout > age ; cout > roll_no ; } void Display_data(void) { cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Hybrid Inheritance

    Q29.Describe Hybrid Inheritance with exampleAns.There could be a situation where we need to apply two or more types of inheritance for instance consider a case processing state of result assuming that voltage for the sports before finalization of result.

    Class stud{ rn ,name;};

    Class test : virtual public stud{

    m1,m2,m3;};

    class score : virtual public stud{ int wt;

    };class result : public test, public score

    {

    };class test is derived from student & class test is also derived from student.

    From both test & score due to multiple path that it gets result of student.

    Q30.Demonstrate Hybrid inheritance with programAns. Hybrid inheritance

    #include class mm {

    protected: int rollno;

    public: void get_num(int a) {

    rollno = a; }

    void put_num() {

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    int sub2; public:

    void get_marks(int x,int y) {

    sub1 = x; sub2 = y;

    } void put_marks(void)

    { cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    std1.get_marks(10,20); std1.get_extra(33.12); std1.disp(); return 0; }

    OutputRoll Number Is: 10

    Subject 1: 10 Subject 2: 20 Extra score:33.12

    Total: 63.12

    ExplanationIn the above example the derived class "res" uses the function "put_num()". Here the "put_num()" function is derived first to class "marks". Then it is derived and used in class "res". This is an example of "multilevel inheritance-OOP's concept". But the class "extra" is inherited a single time in the class "res", an example for "Single Inheritance". Since this code uses both "multilevel" and "single" inheritence it is an example of "Hybrid Inheritance".

    Q31.Program to Demonstrate Hybrid InheritanceAns. Hybrid inheritance

    #include#includeclass stu{protected: int rno;public: void get_no(int a){rno=a; }void put_no(void) { out

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    }void put_marks(){ cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Roll no 123Marks obtained : part1=27.5Part2=33Sports=6Total score = 66.5

    Q32.List Some of the exception with inheritance Ans. Some of the exceptions to be noted in C++ inheritance are as follows

    The constructor and destructor of a base class are not inherited the assignment operator is not inherited the friend functions and friend classes of the base class are also not inherited.

    There are some points to be remembered about C++ inheritance. The protected and public variables or members of the base class are all accessible in the derived class. But a private member variable not accessible by a derived class. It is a well known fact that the private and protected members are not accessible outside the class. But a derived class is given access to protected members of the base class.

    Virtual Base ClassQ33.Describe what do you mean by Virtual base classAns. Virtual Base Class

    The use of both multiple and multilevel inheritance along with hierarchical inheritance as given in the figure.

    The child has two base classes which themselves have common base class grandparent. The child inherits the properties of grandparent via to separate class grandparent is sometimes referred as indirect base class. The child has duplicate set of data members inherited from grandparent this introduces the ambiguity due to multiple paths & can be avoided by making common base class as a virtual base class.

    Using the keyword virtual in this example ensures that an object of Derived class inherits only one subobject of parent class .

    Class grandparent{};

    class parent1 : virtual public grandparent{};

    class parent2 : private virtual grandparent{};

    When a class is made virtual base class C++ takes necessary care to see that only one copy of class is inherited regardless of how many inherited paths exist.

    Q34.Write Program to demonstrate Virtual Base Class in c++Ans. Program to demonstrate Virtual Base Class#include#include

    Grand Parent

    Parent2

    Child

    Parent1

    35

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    class student { protected: int roll_number; public: void get_number(int a) { roll_number=a; } void put_number(void) { cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    class result:public test, public sports { float total; public: void display(void); };

    void result ::display(void) { total=part1+part2+score; put_number(); put_marks(); put_score(); cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    {public: PoweredDevice(int nPower)

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    constructor calls are simply ignored because Copier is responsible for creating the PoweredDevice, not Scanner or Printer. However, if we were to create an instance of Scanner or Printer, the virtual keyword is ignored, those constructor calls would be used, and normal inheritance rules apply.

    Third, if a class inherits one or more classes that have virtual parents, the most derived class is responsible for constructing the virtual base class. In this case, Copier inherits Printer and Scanner, both of which have a PoweredDevice virtual base class. Copier, the most derived class, is responsible for creation of PoweredDevice.

    Note that this is true even in a single inheritance case: if Copier was singly inherited from Printer, and Printer was virtually inherited from PoweredDevice, Copier is still responsible for creating PoweredDevice.

    Abstract ClassQ36.What is abstract class ? state its purposeAns.

    An abstract class is one that is not used to create objects. An abstract class is designed only to act as a base class (to be inherited by other classes). It is a design concept in program development and provides a base upon which other classes may be built.

    An abstract class contains at least one pure virtual function. In the class declaration, if the declaration of a virtual member function is done by appending 0 zero to the function declaration then the function is pure virtual function.

    class Base {

    public:virtual void func() = 0;

    };An abstract class cannot be used as a parameter type, a function return type, or

    the explicit conversion type.The most importtant thing is that one cannot declare the object of an bastract class.However, declaring pointers and references to an abstract class is possible.

    As virtual member functions can be inherited, a class derived from an abstract base class can also be abstract unless overriding of each pure virtual function in the derived class is done.For example

    class Base {

    public:virtual void func1() = 0;

    };class Derived : public Base

    {void func2();

    };int main()

    {39

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Derived obj;}

    The compiler does not allow the declaration of object obj because Derived is an abstract class and it inherited the pure virtual function func1() from Base class. The declaration of object obj will be allowed by compiler if function is defined as Derived :: func2().

    Constructor in Derived ClassQ37.Explain how constructors are used in Derived classAns.A constructor plays a vital role in initializing an object.

    As long as a base class constructor does not take any arguments, the derived class need not have a constructor function.

    However, if a base class contains a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructor. Remember, while applying inheritance, we usually create objects using derived class. Thus, it makes sense for the derived class to pass arguments to the base class constructor.

    When both the derived and base class contains constructors, the base constructor is executed first and then the constructor in the derived class is executed.

    In case of multiple and Multilevel inheritance, the base class is constructed in the same order in which they appear in the declaration of the derived class. Similarly, in a multilevel inheritance, the constructor will be executed in the order of inheritance.

    Derived constructor (arg 1, arg 2, arg d . . . . . . . arg n);Base1 (arg1),Base2 (arg2),.base n (arg n)

    {d=arg d;

    }

    The derived class takes the responsibility of supplying the initial values to its base class. The constructor of the derived class receives the entire list of required values as its argument and passes them on to the base constructor in the order in which they are declared in the derived class. A base class constructor is called and executed before executing the statements in the body of the derived class.

    The header line of the derived-constructor function contains two parts separated by a colon (:). The first part provides the declaration of the arguments that are passed to the derived class constructor and the second part lists the function calls to the base class.

    Example: D(int a1, int a2, int b1, int b2, int d): A(a1, a2), B(b1, b2) {

    o d = d1; }

    40

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    A(a1, a2) invokes the base constructor A() and B(b1, b2) invokes another base class constructor B(). The constructor D() supply the values i.e. a1, a2, b1, b2 (to A() and B()) and to one of its own variables d1.

    Hence, the assignment of the values will be as follows: When an object of D is created, D object-name(5, 12, 7, 8, 30); a1

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    y = j;cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Ans. class beta{

    int y;public:

    beta(int j){

    y = j;cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Q40.Write program to use Multilevel inheritance with constructor Ans. Multilevel inheritance with constructor

    #include class alpha{

    int x;public:

    alpha(int i){

    x = i;cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    int main(){

    gamma g(5, 10.75, 20, 30);cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    baseA::~baseA(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    ~derivedD(); //destructor

    };

    baseA::~baseA(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Member functions of a nested class follow regular access rules and have no special access privileges to members of their enclosing classes. Member functions of the enclosing class have no special access to members of a nested class.

    Example class A { };class B { };class C{

    A a1;B b1;Public:-----------

    };All the objects of C class will contain the object A1 & B1. this kind of

    relationship is called HAS_TO relationship which is called as containership or nesting of classes. While in inheritance the type of relationship is kind of relationship.Example

    Class A

    Class BC c1;

    B is kind of A // InheritanceB has object of C //Containership

    One can define member functions and static data members of a nested class in namespace scope. For example, in the following code fragment, you can access the static members x and y and member functions f() and g() of the nested class nested by using a qualified type name. Qualified type names allow you to define a typedef to represent a qualified class name. You can then use the typedef with the :: (scope resolution) operator to refer to a nested class or class member, as shown in the following example:

    Example codeclass outside

    {public: class nested { public: static int x; static int y;

    Class C

    48

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    int f(); int g(); };};int outside::nested::x = 5;int outside::nested::f() { return 0; };

    typedef outside::nested outnest; // define a typedefint outnest::y = 10; // use typedef with ::int outnest::g() { return 0; };

    However, using a typedef to represent a nested class name hides information and may make the code harder to understand.

    Q44.Write c++ program to implement nesting of classAns. Nested class is a class defined inside a class, that can be used within the scope of the class in which it is defined. In C++ nested classes are not given importance because of the strong and flexible usage of inheritance. Its objects are accessed using "Nest::Display".Example

    #include #include conio.h> class Nest { public: class Display {

    private: int s;

    public: void sum( int a, int b) {

    s =a+b; }

    void show( ) {

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    ExplanationIn the above example, the nested class "Display" is given as "public" member of

    the class "Nest".

    Programs based on Inheritance

    Program -1 Write program to implement the inheritance shown in figure.Ans.class student {

    protected: int roll_no;

    public: void get_roll(int a)

    { roll_no=a;

    } void put_roll(void)

    { cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    { score=s;

    } void put_score(void)

    { cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    }void disp()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    };void main() {

    result r;r.getd();r.getd1();r.getd2();r.cal();r.disp();r.disp1();r.disp3();

    }Program-4Write program to implement the inheritance shown in figure.Ans.Multilevel Inheritance Example

    /*Program to illustrates Multi-level Inheritance with public derivation */

    #include #include

    /*----------------------Class Interfaces-------------------------*/class employee // base class

    {char name[10];int empno;

    public :void set(int, char*);void display();

    };class manager : public employee // Level - 1

    {int no_of_projects;

    public:void set(int, char*, int); // overriding functionsvoid display();

    };

    class area_manager : public manager // Level - 2{

    char location[10];public:

    void set(int, char*, int, char*);// overriding functionsvoid display();

    };

    /*----------------------Class Implementations---------------------*/

    // member function definitions for 'employee'

    53

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    void employee::set(int c, char* s){

    empno = c;strcpy(name, s);

    }void employee::display()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Hierarchical Inheritance/*Program to illustrates Multi-level Inheritance with public derivation */

    #include #include

    /*----------------------Class Interfaces-------------------------*/class employee // base class

    {char name[10];int empno;

    public :void set(int, char*);void display();

    };class manager : public employee // Level - 1

    {int no_of_projects;

    public:void set(int, char*, int); // overriding functionsvoid display();

    };class area_manager : public manager // Level - 2

    {char location[10];

    public:void set(int, char*, int, char*);// overriding functionsvoid display();

    };

    /*----------------------Class Implementations---------------------*/

    // member function definitions for 'employee'

    void employee::set(int c, char* s){

    empno = c;strcpy(name, s);

    }void employee::display()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    employee::set(c, s);no_of_projects = p;

    }void manager::display()

    {employee::display();cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    {int balance;

    public:void set(int,char*,int);// Overriding functionsvoid display();

    };class Deposite

    {int amount;char maturity_date[9];

    public:void set(int, char*);void display();

    };class DepositeAccount : public Account, public Deposite

    {char opening_date[9];

    public:void set(int,char*,int,char*,char*);// Overriding functionsvoid display();

    };class ShortTerm : public DepositeAccount

    {int no_of_months;

    public:void set(int,char*,int,char*,char*,int);// Overriding functionsvoid display();

    };class LongTerm : public DepositeAccount

    {int no_of_years;int loan_taken;

    public:void set(int,char*,int,char*,char*,int,int);// Overriding functionsvoid display();

    };/*----------------------Class Implementations---------------------*/// member function definitions for 'Account'void Account::set(int a, char* b)

    {number = a;strcpy(name, b);

    }void Account::display()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    // member function definitions for 'SavingsAccount'void SavingsAccount::set(int a, char* b, int c)

    {Account::set(a,b);balance = c;

    }void SavingsAccount::display()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    // member function definitions for 'LongTerm'void LongTerm::set(int a, char* b, int c, char* d, char* e, int f, int g)

    {DepositeAccount::set(a,b,c,d,e);no_of_years = f;loan_taken = g;

    }void LongTerm::display()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Ans,Class Student

    {int Rollno;char name[40];

    public :void getStudent( int rn , char nm[])

    {Rollno = rn;Strcpy(name,nm);

    }void displayStudent()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    }};

    void main(){

    Exam E1;E1.getStudent(123,Manoj);E1.getExam(OOP);

    Library L1;E1.getLibrary(143);E1.displayStudent();E1.displayExam();L1.displayLibrary();getch();

    }

    Program-2Write a program for following hierarchy inheritance in the given fig. Assume suitable member function

    Ans.Class Staff

    {int staffcodeno;char staffname[40];

    public :void getStaffDetails( int sfc , char snm[])

    {staffcodeno = sfc;Strcpy(staffname,snm);

    }void displayStaff()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    {

    char Teacher_grade;public :

    void getGrade( char gr){

    teacher_grade = gr;}

    void displayTeacher(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Class Customer{

    int phone;char cname[40];

    public :void getCustomer( int ph , char cnm[])

    {Phone = ph;Strcpy(name,nm);

    }void displayCustomer ()

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    {cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    count-- ;i++ ;

    }}

    void displayString(){

    cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    int mark1 , makr2;public :

    void getMarks( int m1 , int m2){

    mark1 = m1;mark2 = m2;

    }void displayMarks()

    {Cout

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    b. Identify inheritance shown n following figure, Implement it by assuming suitable member functions.

    c. Explain concept of virtual base class with suitable example.Summer 2008

    a. What do you mean by inheritance ?give different types if inheritanceb. Write a program for following hierarchy inheritance in the given fig. Assume

    suitable member function

    c. Write a program to implement inheritance as shown in figure.Assume suitable data data member function to accept and display function

    Staff Code

    Teacher Subject Officer grade

    Customer

    NamePhone_No

    Depositor

    Acc_noBalance

    Borrower

    Loan_noLoan_amm

    67

  • Prof.Manoj S.Kavedia (9860174297)([email protected])

    Winter 2008a. Define Multiple Inheritance. Give example.b. What is an abstract base class.c. What is virtual base class? Explain with suitable exampled. Write a code to reverse a string by overloading method

    Summer 2009a. What is inheritance ? Mention and explain three types of inheritance you know.b. Explain multilevel inheritance with suitable example program.

    Winter 2009a. What does inheritance means in C++? Describe syntax of single inheritance.b. When do we make a class virtual? What is an

    abstract class?c. What is meant by overloading and overriding?d. Write a program that illustrate multiple

    inheritancee.

    Summer 2010a. What does inheritance means in c++?Describe

    syntax of Single Inheritanceb. When do we make virtual base class? Explain

    with suitable example.c. What is meant by overloading and overridingd. Identify Inheritance shown in following Figure

    No. 1 Implement it by using suitable member-function

    68

    Features or Advantages of Inheritance Q2.What is not inherited from the base class?