44 inheritance - yolakavediasir.yolasite.com/resources/chapter-4-inheritance.pdf · q4.list and...

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

Upload: others

Post on 20-Jan-2020

1 views

Category:

Documents


0 download

TRANSCRIPT

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 Inheritance

SyllabusConcepts 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 <iostream.h># include <conio.h>/*----------------------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 << "n1 = " << n1 << "\n";cout << "n2 = " << n2 << "\n";

}

// member function definitions for class Bvoid B:: read _n2_and_b(int x, int y){

5

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

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

}void B::display_b(){

cout << "b = " << b << "\n";}

/*----------------------Class definitions ends here---------------*/void main(void){

B obj;

// accessing public member function of the base directlyobj. read _n1(100);obj. read _n2_and_b(200,300);

// accessing public member function of the base directlyobj.display_n1n2();obj.display_b();

}

Output a1 = 100a2 = 200b = 300

ExplanationClassA is declared to have one private data member n1 and three members,

n2(data) and set_nl() and display_n1n2() which are the member functions. set_n1() is used to initialise al which is a private data member and cannot be directly accessed.

Class B inherits A publically. That means all the public members of A are directly accessible to the objects of B. The member function set_n2_andb() initialise b, its own private member and public member n2 of the base.

The public members of the base remains the public members of the derived or extended class B as the public visibility mode is used in the derivation inheritance. One can access the public member of the base class through the object of the derived class.

Q8.Program to demonstrate Single InheritanceAns.

#include <iostream.h>#include <conio.h>class Value { protected: int val; public: void set_values (int a) {

6

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 << "The Cube of 5 is::" << cub.cube() << endl; return 0; }

OutputThe Cube of 5 is:: 125

ExplanationIn the above example the derived class "Cube" has only one base class "Value".

This is the single inheritance OOP's concept.

Q9.Write c++ program to implement single public inheritanceAns. Single Public Inheritance

# include<iostream.h>#include<conio.h>Class B{

int a;public:

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

};

class D : public B{

int c;public:

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

};

7

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<<”a = “ <<a << “\n”;}

void D :: mul(){

c = b * get_a ();}

Void D :: display(){

cout << “a = “ <<get_a() << “\n”;cout << “b = “<< b <<”\n”;cout << “c = “<< c <<”\n \n “ ;

}int main()

{D d;d.get_ab();d.mul(); d.show_a();d.display();

d.b = 20;d.mul();d.disp1ay();return 0;

}

Q10.Describe single private inheritanceAns. In the private derivation (or inheritance) the public members of the base becomes the private member of the derived class. Hence, they cannot be directly accessible through the dot (.) operator using the object of the derived class as

Object.member()Hence the only way to access the public members of the base, which are now the private members of the derived class ie access them in the body of the members of the derived class. It is same as accessing any other private member of the class.

Q11.Write c++ program to implement single private inheritance8

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

Ans. Singe private inheritance # include<iostream.h>#include <conio.h>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){

Cout<<”Enter values for a and b” ;Cin>>a>>b;

} int B :: get_a()

{return a;

}void B :: show_a()

{Cout<<”a = “ <<a << “\n”;

}

void D :: mul(){

get_ab();c = b * get_a ();

}Void D :: display()

{show_a();cout << “b = “<< b <<”\n”;cout << “c = “<< c <<”\n \n “ ;

}int main()

{9

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 can’t 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 can’t 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 can’t 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 <iostream.h>#include<conio.h>/*----------------------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 << "a1 = " << a1 << "\n";

// accessing the public member of the classcout << "a2 = " << a2 << "\n";

// accessing the private member of the classcout << "b = " << b << "\n";

12

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<<”Protected member with private inheritance :\n”obj1.display();getch();

}

Output Protected member with private inheritancea1=101a2=202b=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 private inheritance.

As stated above protected member is like a private member but accessible to the derived class protected member and private data member become private when inherited in private mode. So both the data members Al and A2 of class A and one data member ‘b’ of class B are accesses in member function of class B

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

#include <iostream.h>#include<conio.h>/*----------------------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 A13

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 << "a1 = " << a1 << "\n";

// accessing the private member of the classcout << "b = " << b << "\n";

}

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

B obj1;

// Accessing the public member of the base class obj1.a2=202;obj1.set(101,303);cout<< “Protected member with public inheritance :\n”cout<< “a2 = ” <<obj1.a2 <<”\n”;obj1.display();getch();

}

Output Protected member with public inheritancea2=202a1=101

14

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 <iostream.h>#include <string.h>/*----------------------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 << "Employee Information : \n";}void employee::display(){

cout << "Employee No. : " << empno << "\n";cout << "Name : " << name << "\n";

}// member function definitions for 'manager'void manager::set(int c, char* s, int p){

no_of_projects = p;employee::set(c, s);// base class function explicitly invoked

}void manager::display_heading(){

cout << "Manager Details : \n";}void manager::display_projects(){

cout << "No of Projects currently handling : ";cout << no_of_projects << "\n";

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

manager manoj;

manoj.set(1000, "Manoj", 4);16

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, manager’s 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 <iostream.h>#include <conio.h>class mm { protected: int rollno; public: void get_num(int a) {

rollno = a; }

void put_num() {

cout << "Roll Number Is:\n"<< rollno << "\n"; }

};class marks : public mm { protected:

int sub1; int sub2;

public: void get_marks(int x,int y)

{ sub1 = x; sub2 = y; }

void put_marks(void) { cout << "Subject 1:" << sub1 << "\n";

cout << "Subject 2:" << sub2 << "\n";19

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 << "Total:"<< tot; }

};int main() { res std1; std1.get_num(5); std1.get_marks(10,20); std1.disp(); return 0; }

Output Roll Number Is: 5 Subject 1: 10 Subject 2: 20 Total: 30

ExplanationIn the above example, the derived function "res" uses the function

"put_num()" from another derived class "marks", which just a level above. This is the multilevel inheritance OOP's concept in C++.

Q21.Program to Implement MultiLevel inheritanceAns.

/********* Implementation Of Multilevel Inheritance *********/

#include< iostream.h>#include< conio.h>

class student // Base Class{ protected: int rollno;

20

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 <iostream.h>#include<conio.h>using 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 << "The area of the square is::" << i << endl; }

class Area: public Square, public CShow { public:

int area() {

return (l *l); }

};int main () { Area r; r.set_values (5); r.show(r.area()); return 0;}

OutputThe area of the square is:: 25

ExplanationIn the above example the derived class "Area" is derived from two base

classes "Square" and "CShow". This is the multiple inheritance OOP's concept in C++.

Q24.Demonstrate Multiple inheritance with programAns. Multiple inheritance

#include<iostream.h>#include<conio.h>

class M { protected: int m; public: void get_m(int); };

class N { protected: int n; public: void get_n(int);

24

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<<"m ="<<M<<"\N"; cout<<"n ="<<N<<"\N"; cout<<"m*n="<<M*N<<"\N"; }void main() { P p; p.get_m(10); p.get_n(10); p.display(); getch(); }

Q25.Write Program to generate marksheet using multiple InheritanceAns. Program to generate marksheet using multiple Inheritance

#include<iostream.h>#include<stdio.h>#include<dos.h>class student {

int roll;char name[25];char add [25];char *city;public: student(){

cout<<"welcome in the student information system"<<endl;}void getdata(){

25

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

cout<<"\n enter the student roll no.";cin>>roll;cout<<"\n enter the student name";cin>>name;cout<<\n enter ther student address";cin>>add;cout<<"\n enter the student city";cin>>city;

}void putdata(){

cout<,"\n the student roll no:"<<roll;cout<<"\n the student name:"<<name;cout<<"\n the student coty:"<<city;

}};class mrks: public student{

int sub1;int sub2;int sub3;int per;public: void input(){

getdata();cout<<"\n enter the marks1:"cin>>sub1:cout<<"\n enter the marks2:";cin>>sub2;cout<<\n enter the marks3:";cin>>sub3;

}void output(){

putdata();cout<<"\n marks1:"<<sub1;cout<<"\n marks2:"<<sub2;cout<<"\n marks3:"<<sub3;

}void calculate (){

per= (sub1+sub2+sub3)/3;cout<<"\n tottal percentage"<<per;

}}; void main(){

26

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

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

cout<<\n1.input data";cout<<\n2.output data";cout<<\n3. Calculate percentage";cout<<\n4.exit";cout<<\n enter the choice";cin>>ch;switch (ch){

case 1:m1.input();count++;break;

case2:

m1.output();break;

case3:m1.calculate();break;

}} while (ch!=4);

}Hierarchical Inheritance

Q26.Describe Hierarchical Inheritance with exampleAns.Additional members are added through inheritance to extend the capabilities of the class. Where many other below that level level shares certain feature of one.The figure shows hierarchical classification of the university is there could be the branches move than one as given below. The class is more collaborate with its branch as shown.

The base class would include all the features, which are common to all class the declaration syntax can be follows.

Class University{ ---------- };

class art: visibility mode University { ----------};

class engg : visibility mode University{ -------- };

class medical : VM universityclass CM : visibility mode Engg

{ -------- };

University

Arts Engg. Medical

CM IF

27

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

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

Q27.Demonstrate Hierarchical inheritance with programAns. Hierarchical inheritance

#include <iostream.h>#include <conio.h>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 << "The square value is::" << s.sq() << endl; Cube c; c.set_values (20); cout << "The cube value is::" << c.cub() << endl; return 0; }

Output The square value is:: 100 The cube value is::8000Explanation

28

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<iostream.h>#include<conio.h>const 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 << "\n\t Enter the first name: " ; cin >> F_name ; cout << "\t Enter the second name: "; cin >> L_name ; cout << "\t Enter the age: " ; cin >> age ; cout << "\t Enter the roll_no: " ; cin >> roll_no ; } void Display_data(void) { cout << "\n\t First Name = " << F_name ; cout << "\n\t Last Name = " << L_name ; cout << "\n\t Age = " << age ; cout << "\n\t Roll Number = " << roll_no ; } };class arts : public student { private: char asub1[len] ; char asub2[len] ; char asub3[len] ; public: void Enter_data(void) { student :: Enter_data( ); cout << "\t Enter the subject1 of the arts student: "; cin >> asub1 ; cout << "\t Enter the subject2 of the arts student: "; cin >> asub2 ; cout << "\t Enter the subject3 of the arts student: "; cin >> asub3 ; } void Display_data(void) { student :: Display_data( );

29

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

cout << "\n\t Subject1 of the arts student = " << asub1 ; cout << "\n\t Subject2 of the arts student = " << asub2 ; cout << "\n\t Subject3 of the arts student = " << asub3 ; } };

class commerce : public student { private: char csub1[len], csub2[len], csub3[len] ; public: void Enter_data(void) { student :: Enter_data( ); cout << "\t Enter the subject1 of the commerce student: "; cin >> csub1; cout << "\t Enter the subject2 of the commerce student: "; cin >> csub2 ; cout << "\t Enter the subject3 of the commerce student: "; cin >> csub3 ; } void Display_data(void) { student :: Display_data( ); cout << "\n\t Subject1 of the commerce student = " << csub1 ; cout << "\n\t Subject2 of the commerce student = " << csub2 ; cout << "\n\t Subject3 of the commerce student = " << csub3 ; } };

void main(void) { arts a ; cout << "\n Entering details of the arts student\n" ; a.Enter_data( ); cout << "\n Displaying the details of the arts student\n" ; a.Display_data( ); science s ; cout << "\n\n Entering details of the science student\n" ; s.Enter_data( ); cout << "\n Displaying the details of the science student\n" ; s.Display_data( ); commerce c ; cout << "\n\n Entering details of the commerce student\n" ; c.Enter_data( ); cout << "\n Displaying the details of the commerce student\n"; c.Display_data( ); }

30

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 <iostream.h>class mm {

protected: int rollno;

public: void get_num(int a) {

rollno = a; }

void put_num() {

cout << "Roll Number Is:"<< rollno << "\n"; }

};class marks : public mm {

protected: int sub1;

Student

Test

Result

Score

31

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 << "Subject 1:" << sub1 << "\n"; cout << "Subject 2:" << sub2 << "\n"; }

};

class extra {

protected: float e;

public: void get_extra(float s)

{e=s;

} void put_extra(void) {

cout << "Extra Score::" << e << "\n"; }

};

class res : public marks, public extra{ protected:

float tot; public:

void disp(void) {

tot = sub1+sub2+e; put_num(); put_marks();

put_extra(); cout << "Total:"<< tot;

} };

int main() { res std1; std1.get_num(10);

32

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<iostream.h>#include<conio.h>class stu{protected: int rno;public: void get_no(int a){rno=a; }void put_no(void) { out<<"Roll no"<<rno<<"\n"; }};class test:public stu{ protected: float part1,part2;public: void get_mark(float x,float y) { part1=x; part2=y;

33

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

}void put_marks(){ cout<<"Marks obtained:"<<"part1="<<part1<<"\n"<<"part2="<<part2<<"\n";}};class sports{ protected: float score;public: void getscore(float s) { score=s; }void putscore(void){ cout<<"sports:"<<score<<"\n"; }}; class result: public test, public sports{ float total;public: void display(void);};void result::display(void){ total=part1+part2+score; put_no(); put_marks(); putscore(); cout<<"Total Score="<<total<<"\n";}int main(){ clrscr(); result stu; stu.get_no(123); stu.get_mark(27.5,33.0); stu.getscore(6.0); stu.display(); return 0;}

Output

34

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<iostream.h>#include<conio.h>

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<<"Roll No. "<<ROLL_NUMBER<<"\n"; } };

class test:virtual public student { protected: float part1, part2; public: void get_marks(float x, float y) { part1=x; part2=y; } void put_marks(void) { cout<<"Marks obtained :\n"; cout<<"Part1 = "<<PART1<<"\n"; cout<<"Part2= "<<PART2<<"\n"; } };

class sports : public virtual student { protected: float score; public: void get_score(float s) { score=s; } void put_score(void) { cout<<"Sports wt: "<<SCORE<<"\n\n"; } };

Student

Test

Result

Sport

36

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<<"Total Score : "<<TOTAL<<"\n"; }int main() { result student_1; student_1.get_number(678); student_1.get_marks(30.5,25.5); student_1.get_score(7.0); student_1.display(); return 0; }

Output Roll No: 678 Marks obtained: Part1 = 30.5 Part2 = 25.5 Sports wt: 7 Total Score: 63

Explanation The Result has two base classes test and sports which themselves have common base class student. The result inherits the properties of student via two separate class student class which is sometimes referred as indirect base class.

The result has duplicate set of data members inherited from student 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 sub object of parent class .Hence now result class will inherit only one set of member from student class , which is grand parent class.

Q35.Write Program to demonstrate Virtual Base Class in c++Ans.

class PoweredDevice37

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

{public: PoweredDevice(int nPower)

{cout << "PoweredDevice: " << nPower << endl;

}};

class Scanner: virtual public PoweredDevice{ public:

Scanner(int nScanner, int nPower): PoweredDevice(nPower) {

cout << "Scanner: " << nScanner << endl; }

};

class Printer: virtual public PoweredDevice{

public: Printer(int nPrinter, int nPower): PoweredDevice(nPower)

{cout << "Printer: " << nPrinter << endl;

}};

class Copier: public Scanner, public Printer{public:

Copier(int nScanner, int nPrinter, int nPower): Scanner(nScanner, nPower), Printer(nPrinter, nPower), PoweredDevice(nPower) { }

};

OutputPoweredDevice: 3Scanner: 1Printer: 2

ExplanationAs you can see, PoweredDevice only gets constructed once. First, virtual base classes are created before non-virtual base classes, which ensures all bases get created before their derived classes.

Second, note that the Scanner and Printer constructors still have calls to the PoweredDevice constructor. If we are creating an instance of Copier, these

38

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 <- 5 a2 <- 12 b1 <- 7 b2 <- 8 d1 <- 30• The constructors for a virtual base class are invoked before any non-virtual base

classes. If there are multiple virtual base classes, then they are invoked in the order in which they are declared.

Method Of Inheritance Order Of ExecutionClass A: public b { }Class A: public b,Public c { }class A : private c, virtual public d { }

BA

BCA

BCDA

Q38.Write c++ program to implement constructor in derived class(Multiple Inheritance)Ans.

#include <iostream.h>class alpha{

int x;public:

alpha(int i){

x = i;cout<<”Alpha initialized “ << “\n”;

}void show_x(void)

{cout << “ x = “ << x << “ \n”;

}};class beta{

int y;public:

beta(int j){

41

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

y = j;cout<<”Beta initialized “ << “\n”;

}void show_y(void) {

cout << “ y = “ << y << “ \n”;}

};

class gamma: public beta, public alpha{

int m, n;public :

gamma(int a, float b, int c, int d) : alpha(a), beta(b){

m = c;n = d;cout << “gamma initialized \n”;

}void show_mn(void)

{cout << “m = “ << m <<”\n”;cout << “n = “ << n <<”\n”;

}};

int main(){

gamma g(5, 10.75, 20, 30);cout << “\n”;g.show_x(); g.show_y(); g.show_mn();return 0;

}

Explanation There are three class alpha, beta and gamma. gamma class is inherited from

alpha and beta. Since in the sequence of inheritance is beta class if first and alpha class is next , first constructor call will be beta class and then of alpha class. And if the sequence is like this then

class gamma:public alpha, public betathen constructor of alpha class is first called and then constructor for beta class will be called.

Inheritance with constructor

Q39.Write program to use single inheritance with constructor 42

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

Ans. class beta{

int y;public:

beta(int j){

y = j;cout<<”Beta initialized “ << “\n”;

}void show_y(void) {

cout << “ y = “ << y << “ \n”;}

};

class gamma: public beta{

int m, n;public :

gamma(int a, int c, int d) : beta(a){

m = c;n = d;cout << “gamma initialized \n”;

}void show_mn(void)

{cout << “m = “ << m <<”\n”;cout << “n = “ << n <<”\n”;

}};

int main(){

gamma g(5, 20, 30);cout << “\n”;g.show_y(); g.show_mn();return 0;

}Explanation

In the above example class gamma is derived from class beta. When an object of gamma is created , constructor of class gamma is called which has three parameters, which in turn calls the constructor of the base class beta , to which one is passed. Hence first constructor of class beta is executed and then constructor of class gamma is executed which is derived class.

43

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

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

#include <iostream.h>class alpha{

int x;public:

alpha(int i){

x = i;cout<<”Alpha initialized “ << “\n”;

}void show_x(void)

{cout << “ x = “ << x << “ \n”;

}};class beta: public alpha{

int y;public:

beta(int a , int b) : alpha(a){

y = b;cout<<”Beta initialized “ << “\n”;

}void show_y(void) {

cout << “ y = “ << y << “ \n”;}

};

class gamma: public beta{

int m, n;public :

gamma(int a, float b, int c, int d) : beta(a, b){

m = c;n = d;cout << “gamma initialized \n”;

}void show_mn(void)

{cout << “m = “ << m <<”\n”;cout << “n = “ << n <<”\n”;

}};

44

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

int main(){

gamma g(5, 10.75, 20, 30);cout << “\n”;g.show_x(); g.show_y(); g.show_mn();return 0;

}Explanation

There are three class alpha, beta and gamma. Class beta is inherited from class alpha and gamma class is inherited from beta.

When the object of class gamma is created it has four parameter passed to it.Which in turn calls the constructor of its base class beta to which two parameter are passed.

Now beta class call the constructor of alpha class to which one argument is passed.Hence first the constructor of alpha class is executed , then constructor of beta class is executed and then finally control is transferred to gamma class constructor and all member are intialised in this manner.

Destructor in Derived classQ41.Describe the functioning of destructor in case of inheritanceAns. It has been seen that destructor is a special member function. It is invoked automatically to free the memory space which was allocated by the constructor functions. Whenever an object of the class is getting destroyed, the destructors are used to free the heap area so that the free memory space may be used subsequently. It has seen demonstrated that constructors in an inheritance hierarchy fire from a base class to a derived class. Destructors in an inheritance hierarchy fire from a derived class to a base class order, i.e., they fire in the reverse order of that of the constructors,

ExampleA program to demonstrate how the destructor member function gets fired

from the derived class objects to the base class.// destructors under inheritance

#include <iostream.h> class baseA

{public :

~baseA() //destructor};

class derivedB : public baseA{

public:~derivedB(); //destructor

};45

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

baseA::~baseA(){

cout<< “\nbaseA class destructor”;}

derivedB::~derivedB(){

cout<< “\nderivedB class destructor”;}

void main(){

derviedB objb();}

Output of the above programderivedB class destructorbaseA class destructor

Q42.Program to demonstrate multiple , declare , invoke all the destructor member function under multiple inheritanceAns.// destructor under multiple inheritance

#include <iostream.h> class baseA

{public :

~baseA() //destructor};

class derivedB : public baseA{

public:~derivedB(); //destructor

};

class derivedC : public derivedB{

public:~derivedC() ; //destructor

};

class derivedD : public derivedC{

public:46

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

~derivedD(); //destructor

};

baseA::~baseA(){

cout<< “\nbaseA class destructor”;}

derivedB::~derivedB(){

cout<< “\nderivedB class destructor”;}

derivedC::~derivedC(){

cout<< “\nderivedC class destructor”;}

derivedD::~derivedD(){

cout<< “\nderivedD class destructor”;}

void main(){

derviedD objD();}

output of programderivedD classderivedC classderivedB classbase class

Nested Class or Container Class

Q43.Describe what is member class ? or nesting of classAns.Inheritance is the mechanism of driving certain properties of one class into another class. C++ supports another way of inheriting the properties of one class into another that is a class can contain the object of another class as its member. I.e. an object can be collection of other objects.

A nested class is declared within the scope of another class. The name of a nested class is local to its enclosing class. Unless you use explicit pointers, references, or object names, declarations in a nested class can only use visible constructs, including type names, static members, and enumerators from the enclosing class and global variables.

47

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 <iostream.h>#include conio.h> class Nest { public: class Display {

private: int s;

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

s =a+b; }

void show( ) {

cout << "\nSum of a and b is:: " << s; }

}; }; void main() {

Nest::Display x; x.sum(12, 10); x.show(); }

OutputSum of a and b is::22

49

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<<"Roll_no:"<<roll_no<<endl;

} };

class test : public student {

protected:float sub1,sub2,sub3;

public: void get_marks(float a,float b,float c) { sub1=a; sub2=b;sub3=c; } void put_marks(void) { cout<<"Sub1="<<sub1<<endl;

cout<<"Sub2="<<sub2<<endl; cout<<"Sub3="<<sub3<<endl; } };

class sports {

protected: float score;

public: void get_score(float s)

50

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

{ score=s;

} void put_score(void)

{ cout<<"Score="<<score<<endl;

} };

class result : public test,public sports { float total; //private member by default

public: void display(void)

{ total=sub1+sub2+sub3+score; put_roll(); put_marks(); put_score(); cout<<"Total="<<total<<endl;

}};int main(){

result s1;s1.get_roll(501); s1.get_marks(60,75.7,89.34);s1.get_score(8.56);s1.display();return (0);

}

Program-2Write program to implement the inheritance shown in figure.Ans

class stud{

protected:int rn;char name[10];

public:void getd(){cout<<”\n Enter Name and Roll Number=”;cin>>rn>>name;

51

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

}void disp()

{cout<<”\n Name =”<<name;cout<<”\n Roll number =”<<rn;

} }class test: public virtual stud

{protected:

float m1,m2,m3;public:

void getd1(){

cin>>m1>>m2>>m3;}

void disp1(){

cout<<m1<<m2<<m3;}

};class score: virtual public stud

{protected:

float spt;public:

void getd2(){

cin>>spt;}

void disp2(){

cout<<spt;}

};class result: public test, public score

{private:

float total;public:

void cal(){

total=m1+m2+m3+spt;}

void disp3(){

cout<<total;}

52

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 <iostream.h>#include <string.h>

/*----------------------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 << "Employee No. : " << empno << "\n";cout << "Name : " << name << "\n";

}// member function definitions for 'manager'

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

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

}void manager::display()

{employee::display();cout << "No of Projects currently handling : ";cout << no_of_projects << "\n";

}// member function definitions for 'area_manager'

void area_manager::set(int c, char* s, int p, char* l){

manager::set(c, s, p);strcpy(location, l);

}void area_manager::display()

{manager::display();cout << "Location : ";cout << location << "\n";

}/*----------------------Class definitions ends here---------------*/

void main(void){

area_manager A;

A.set(1001, "Stavan", 5, "New York");A.display();

}

Program-5Ans.Write program to implement the inheritance shown in figure.

54

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

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

#include <iostream.h>#include <string.h>

/*----------------------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 << "Employee No. : " << empno << "\n";cout << "Name : " << name << "\n";

}// member function definitions for 'manager'

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

55

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

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

}void manager::display()

{employee::display();cout << "No of Projects currently handling : ";cout << no_of_projects << "\n";

}// member function definitions for 'area_manager'

void area_manager::set(int c, char* s, int p, char* l){

manager::set(c, s, p);strcpy(location, l);

}void area_manager::display()

{manager::display();cout << "Location : ";cout << location << "\n";

}/*----------------------Class definitions ends here---------------*/

void main(void){

area_manager A;

A.set(1001, "Stavan", 5, "New York");A.display();

}

Program-6Write program to implement the inheritance shown in figure.Ans.Hybrid Inheritance

/* Program to illustrates Hybrid Inheritance */#include <iostream.h>#include <string.h>/*----------------------Class Interfaces-------------------------*/class Account

{int number;char name[10];

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

};class SavingsAccount : public Account

56

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 << "Number : " << number << "\n";cout << "Name : " << name << "\n";

}57

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 << "Savings Account Details --- \n";Account::display();cout << "Balance : " << balance << "\n";

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

{amount = a;strcpy(maturity_date, b);

}void Deposite::display()

{cout << "Amount : " << amount << "\n";cout << "Maturity Date : " << maturity_date << "\n";

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

{Account::set(a,b);Deposite::set(c,d);strcpy(opening_date, e);

}void DepositeAccount::display()

{Account::display();Deposite::display();cout << "Date of Opening : " << opening_date << "\n";

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

{DepositeAccount::set(a,b,c,d,e);no_of_months = f;

}void ShortTerm::display()

{cout << "Short Term Deposite Account Details --- \n";DepositeAccount::display();cout << "Duration in Months : " << no_of_months << "\n";

}58

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 << "Long Term Deposite Account Details --- \n";DepositeAccount::display();cout << "Duration in Years : " << no_of_years << "\n";cout << "Loan Taken : " << loan_taken << "\n";

}/*----------------------Class definitions ends here---------------*/void main(void)

{SavingsAccount S;S.set(1323, "Stavan", 10000);S.display();cout << "\n";

ShortTerm ST;ST.set(17099, "Kush", 25000, "12/05/02", "12/02/02", 3);ST.display();cout << "\n";

LongTerm LT;LT.set(17169, "Vishwas", 30000, "15/03/04", "15/03/02", 2, 1000);LT.display();cout << "\n";

}

Board Exam Programs

Program -1Identify inheritance shown n following figure, Implement it by assuming suitable member functions.

Class Name :Students

Member Variable :Roll No , Name

Class Name :Exam

Member Variable :Subject Name

Class Name :Library

Member Variable :MemberShip No

59

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<< “\nName =”<<name;cout << “\n Roll Number =”<<Rollno;

}};

Class Exam : public Student{

char subject_name[40];public :

void getExam( char snm[]){

Strcpy(subject_name,snm);}

void displayExam(){

cout<< “\nName of subject =”<<subject_name;

}};

Class Library: public Student{

int membership_no;public :

void getLibrary (int mmno){

membership_no = mmno;}

void displayLibrary(){

cout<< “\MemberShip Number =”<<membership_no;

60

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<< “\nName of Staff =”<<staffname;cout << “\n Code Number of Staff =”<<staffcodeno;

}};

Class Teacher : public Staff

Staff Code

Teacher Subject Officer grade

61

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

{

char Teacher_grade;public :

void getGrade( char gr){

teacher_grade = gr;}

void displayTeacher(){

cout<< “\nGrade of Teacher =”<<teacher_grade;

}};

Class Officer: public Staff{

char Officer_grade;public :

void getGrade( char gr){

Officer_grade = gr;}

void displayOfficer(){

cout<< “\nGrade of Officer =”<<Officer_grade;

}

};void main()

{ Teacher T1;T1.getTeacher(123,“Payal”);T1.getGrade(‘A’);

Officer O1;O1.getGrade(‘B’);T1.displayStaff();T1.displayTeacher();O1.displayOfficier();getch();

}

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

62

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<< “\nCustomer Name =”<<cname;cout << “\n Customer Phone Number =”<<Rollno;

}};

Class Depositor : public Customer{

int accno;int balance;

public :void getDepositor(int ano , int bal)

{accno = ano;balance = bal;

}void displayDepositor()

{cout << “\n Account Number =”<<accno;cout << “\n Balance Amount =”<< bal;

}};

Class Borrower: public Depositor{

int Loanno;int Loanamt;

public :void getBorrower(int lno , int lamt)

{Loanno = lno;Loanamt= lamt;

}void displayBorrower()

Customer

NamePhone_No

Depositor

Acc_noBalance

Borrower

Loan_noLoan_amm

63

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

{cout << “\n Loan Number =”<<Loanno;cout << “\n Loan Amount =”<< Loanamt;

}

};

Void main(){ Borrower B1; B1.getCustomer(323133, “ManojKavedia”); B1.getDepositor(123,43143); B1.getLoan(101,10000); B1.dispCustomer(); B1.dispDepositor(); B1.dispLoan(); getch(); }

Program-4Write a code to reverse a string by overloading methodAns./* Program to perform Reversal of String */#include <iostream.h>#include <conio.h>#include<stdio.h>class ReverseString

{char str[80] , rstr[80];int count;

public :Reverstring()

{ str[0] =’\0’;}

ReverseString( char st[]){ int i ;

count = 0;while (str[count] != '\0') //Find length of string

count++ ;count-- ;

for(i=0 ; i<80 ; i++) //intialise rstr array with 0rstr[i] = 0;

i = 0 ;while (count >= 0) //reverse the String

{rstr[count] = str[i] ;

64

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

count-- ;i++ ;

}}

void displayString(){

cout<< “\nString Entered =” <<str;cout<< “\nReverse string =”<<rstr;

}}

void main ( ){

char line[80] ;ReverseString Rs1();Rs1.displayString();

ReverseString Rs2(“IndiaToday”);Rs2.displayString();getch ( ) ;

}

Program-5Identify ‘Inheritance’ shown in following Figure No. Implement it by using suitable member-function

Class Student{

int Rollno;char name[40];

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

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

}void displayStudent()

{cout<< “\nName =”<<name;cout << “\n Roll Number =”<<Rollno;

}};

Class Test : public Student{

65

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

int mark1 , makr2;public :

void getMarks( int m1 , int m2){

mark1 = m1;mark2 = m2;

}void displayMarks()

{Cout << “\n Subject 1 marks =”<<mark1;Cout << “\n Subject 2 marks =”<<mark2;

}};

Class Result: public Test{

int total;public :

void calculate(){

total = mark1 + mark2;}

void displayResult(){

cout<< “\Total Marks =”<<total;

}};

void main(){

Result R1;R1.getStudent(143,”Nisha”);R1.getMarks(79,68)

R1.calculate();R1.displayStudent();R1.displayMarks();R1.displayResult();getch();

}

Board Question Chapter WiseWinter 2007

a. Elaborate concept of overriding with example66

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