0% found this document useful (0 votes)
136 views50 pages

Unit 3 - Inheritance.ppt

Stydy

Uploaded by

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

Unit 3 - Inheritance.ppt

Stydy

Uploaded by

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

INHERITANCE

What is Inheritance?

•Inheritance is the process by which new classes called


derived classes are created from existing classes called
base classes.

• The derived classes have all the features of the base


class and the programmer can choose to add new
features specific to the newly created derived class.
1
Introduction
example:a programmer can create a base class named
fruit and define derived classes as mango, orange,
banana, etc. Each of these derived classes, (mango,
orange, banana, etc.) has all the features of the
base class (fruit) with additional attributes or
features specific to these newly created derived
classes. Mango would have its own defined
features, orange would have its own defined
features, banana would have its own defined
features, etc.
• This concept of Inheritance leads to the concept of
polymorphism.
2
Features or Advantages of Inheritance:
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 o
inheritance, the programmer can create as many derive
classes from the base class as needed while adding
specific features to each derived class as needed.

3
Saves Time and Effort: The 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.
Increases Program Structure which results in
greater reliability.

Polymorphism
4
• General Format for implementing the concept of
Inheritance:
class derived_classname: access specifier baseclassname

• For example, if the base class is exforsys and the derived


class is sample it is specified as:
class sample: public exforsys

The above makes sample have access to both public and


protected variables of base class exforsys. Reminder
about public, private and protected access specifiers:

5
6

* If a member or variables defined in a class is private,


then they are accessible by members of the same class only
and cannot be accessed from outside the class.
.
* Public members and variables are accessible from
outside the class.
.
* Protected access specifier is a stage between private and
public. If a member functions or variables defined in a class
are protected, then they cannot be accessed from outside
the class but can be accessed from the derived class.
class exforsys {
public:
exforsys(void) { x=0; }
void f(int n1) {
x= n1*5; }
void output(void) { cout<<x; } i nt main(void)
private: {
int x; }; sample s;
class sample: public exforsys s.f(10);
{ public: sample(void) { s1=0; } s.output();
void f1(int n1) s.f1(20);
{ s1=n1*10; } s.output();
void output(void) }
{ exforsys::output();
cout << s1; }
private:
int s1; }; 7
What a derived class inherits
■ Every data member defined in the parent class
(although such members may not always be
accessible in the derived class!)
■ Every ordinary member function of the parent
class (although such members may not always be
accessible in the derived class!)
What a derived class doesn't inherit
■ The base class's constructors and
destructor
■ The base class's assignment operator
■ The base class's friends
What a derived class can add
■ New data members
■ New member functions (also overwrite existing ones)
■ New constructors and destructor
■ New friends
Inheritance in C++
■ The class header is modified to allow a
derivation list consisting of base classes (C++
allows multiple inheritance)

class Foo { };
class Bar : public Foo { };
class More : public Foo, public Bar { };
Public vs private inheritance
■ The public keyword in the inheritance syntax
means that publicly accessible members inherited
from the base class stay publicly accessible in the
derived class
■ But sometimes its preferable to inherit the public
members of a parent in such a way that they
become private in the child
Private inheritance
■ Public members of base class become
private members of derived class
■ Public and protected members are only
available to derived-class member
functions - not to a derived object.
class Motherboard {
public:
void Foo();
protected:
void MooCow(); };
class Computer : private Motherboard
{ public:
void Bar() {
Foo(); // this is okay. It calls Motherboard::Foo()
MooCow(); // this is also okay because Computer can access protected
// Motherboard members
} };
int main()
{ Computer comp;
comp.Foo(); // this is a compiler error.
Return 0; }
Public Inheritance
* Public members of base class remain public
in derived class.
* protected members inherited as
protected and available for further
inheritance.
*private members are not inherited.
class DerivedClass : public BaseClass
#include <iostream> {
using namespace std; int k;
class BaseClass { public:
protected: void setk() {
int i, j; k = i*j; }
public: void showk() {
void set(int a, int b) { cout << k << endl; } };
i = a; int main()
j = b; { DerivedClass ob;
} ob.set(2, 3);
void show() { ob.show();
cout << i << " " << j << endl; ob.setk();
} ob.showk();
}; Return 0; }
Protected inheritance
■ private members of the base class are not
accessible in the derived class (to preserve
encapsulation)
■ Protected qualification allows encapsulated data
members which are not publicly accessible to be
accessible by derived classes
■ ("Protected" members are not accessible from
outside the class, except in derived classes)
#include <iostream>
using namespace std;
class BaseClass {
int i;
i nt main()
Protected: int j;
{
Public: int k;
DerivedClass ob;
void setInt(int a) { i = a; }
int getInt() { return i; }
ob.setk(10);
};
cout << ob.getk() << ' ';
class DerivedClass : protected
BaseClass { ob.setj(12);

public: cout << ob.getj() << ' ';

void setj(int a) {
j = a; } return 0;
void setk(int a) { k = a; } }
int getj() { return j; }
int getk() { return k; } };
Multilevel Inheritance
• ALGORITHM:
• • Start the process
• • Invoke the base class student
• • Invoke the derived class test which in inherited by the class
student
• • Invoke the derived class result which in inherited by the class
test
• • Create an object student1 for the result class
• • Call student1.getno(),assign the value of rno in student class
• • Call student1.getmarks(),assign the marks in test class
• • Call student1.display(),for displaying the result
• • Stop the process
• PROGRAM
• #include
• #include
• class student
• { protected:
• int rno;
• public:
• void getno(int);
• void putno(void);
• };
• void student::getno(int a)
• { rno=a; }
• void student ::putno()
• {cout<<"rollno="<<<<"marks in sub1="<<<<"marks in sub2="<<<<"total="<<
• Class test :public student
• { protected : float sub1,sub2;
• public : void get_marks( float,float);
• void put_marks(void);};
• void test:: get_marks(float x,float y)
• { sub1=x; Int main()
• sub2=y;} { result student1;
student1.get_number(90);
• void test::put_marks()
student1.get_marks(35.6,76
• { cout<<sub1<<sub2;} .5);
• class result :public test { stuydent1.display();
• float total; Return 9;
• public: }
• void display(void);
• };
• void result :: display(void)
• { total=sub1+sub2;
• put_number();
• put_marks();
• cout<<”total=”<<total;
• }
Multiple inheritance
• You can derive a class from any number of base classes.
Deriving a class from more than one direct base class is
called multiple inheritance.
• In the following example, classes A, B, and C are direct
base classes for the derived class X:
• class A { /* ... */ };
• class B { /* ... */ };
• class C { /* ... */ };
• class X : public A, private B, public C { /* ... */ };
Multiple inheritance

•A direct base class cannot appear in the base list of a


derived class more than once:
class B1 { /* ... */ }; // direct base class
class D : public B1, private B1 { /* ... */ }; // error
Hierarchical Inheritance
• Derivation of several classes from a single
class is known as HIERARCHIAL INHERITANCE
• Hirerical inheritance is that inheritance
which have a tree like structure
Student

Arts engineering medical

mech elec civil


Hybrid Inheritance
• It is the inheritance which is a combination of
two or more inheritance of the following :
single, multiple,multilevel and hierarchal
student

Sports
test

result
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)
{cout<<"Roll no"<<rno<<"\n"; } };
class test : public stu
{ protected: float part1,part2;
public: void get_mark(float x,float y)
{ part1=x; part2=y; }
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 : Roll no 123
Marks obtained : part1=27.5
Part2=33
Sports=6
Total score = 66.5
Virtual base classes

Grandparent

Parent 1 Parent 2

child
Virtual base classes
•Virtual base class is a base class acts as an indirect base .
•EX: suppose we have a base class A , which have a data
member x as integer.
•class b: virtual public A
•{ };
•class C : virtual public A
•{ };
•class d: public B,public C
•{ };
•without making classes A and B as virtual class d had two
copies of x.This will arised ambguity problem.
Multiple access (C++ only)
In an inheritance graph containing virtual base classes, a
name that can be reached through more than one path is
accessed through the path that gives the most access.
For example:
class L { public: void f(); };
class B1 : private virtual L { };
class B2 : public virtual L { };
class D : public B1, public B2 {
public:
the function f() is accessed through
void f() {
class B2. Because class B2 is inherited
L::f(); } publicly and class B1 is inherited
}; privately,..
zThe problem
class Animal
{ public:
void eat(); };
class Mammal : public Animal
{ public: void walk(); };
class WingedAnimal : public Animal
{ public: void flap(); };
// A bat is a winged mammal
class Bat : public Mammal, public WingedAnimal {};
The solution
class Animal
{ public:
void eat(); };
class Mammal : public virtual Animal
{ public: void walk(); };
class WingedAnimal : virtual public Animal
{ public: void flap(); };
// A bat is a winged mammal
class Bat : public Mammal, public WingedAnimal {};
Abstract classes
• Abstract class is a class that can not be instantiated, it
exists extensively for inheritance and it must be
inherited.
• There are scenarios in which it is useful to define classes
that is not intended to instantiate
• Abstract classes cannot be used to instantiate objects;
because abstract classes are incomplete, it may contain
only definition of the properties or methods and
derived classes that inherit this implements it's
properties or methods.
Constructors in derived classes

• A constructor plays a vital role in initializing an object


• while using constructors during inheritance, as long as
a base class constructor does not take any arguments,
the derived class need not have a constructor function.
• 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.
Constructors in derived classes

• 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 inheritance, the base class is
constructed in the same order in which they appear in
the declaration of the derived class.
• In a multilevel inheritance, the constructor will be
executed in the order of inheritance.
Constructors in derived classes

• 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 .
• 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.
Constructors in derived classes
Constructors in derived classes
class student
{ private: char name [15];
char address [25];
Public: student (char nm [], char adr [] );
void show (void);
};
class marks : public student
{ private : int sub1, sub2, sub3, total;
Public: marks (char nm [], char adr [], int a, int b, int c) :
student (nm, adr);
void show-detail ( );
};

};
•Initialization list.

• C++ also provides us one more concept to initialize the


member variable of the class when object is created,
known as initialization list.
• Syntax:
• constructor(arg list):intialization-section
• { assignment section}
class base{
private:
int a,b;
public:
//Constructor
base():a(0),b(0)
{
} };
int main(){
//Creating the object of class test
base object;
return 0;
}
class base{
private:
int a,b;
Public: base( int i ,int j):b(i),a(2*j)/ /
/ works fine
base( int i,int j):a(i),b(2*j)
base( int i,int j):b(i),a(b*j)//
{ } }; not work
int main() {
base object(2,3);
return 0;
}
Class gamma:public beta,public alpha
{ int u,v;
Class alpha{ int x; public: gamma(int a, int b,float c):
public: alpha(int i) alpha(a*2),beta(c,c),u(a)
{ x=I;} { v=b;
void show_alpha(void) cout<< gamma const”;}
{ cout<<x<<“\n” } }; void show_gamma(void)
Class beta { float p,q; { cout<<u<<“\n”
public: beta(float a,float cout<<v<<\n”
b):p(a),q(b+p) } };
{ cout <<“beta constru”;} int main( )
void show_beta(void) { gamma g( 2,4,5.3);
{ cout<<p<<q<<“\n” } }; g. show_alpha;
g. show_beta;
g. show_gamma;
Member classes:Nesting of classes

• Inheritance can be implemented by derived classes


and one more approach is containership or nesting
• If class contains objects of another classes this
approach is called containership or nesting .
Class alpha { };
Class beta { };
Class gamma { alpha a;
beta b;
};
Member classes:Nesting of classes

• Creation of an object that contains another object is


different than the creation of an independent object.
• An independent object is created by its constructor
when it is declared with arguments.
• A nested object is created in two stages:
• First, the member objects are created using their
respective constructors and then the other ‘ ordinary’
members are created. This is accomplished using an
initialization list in the constructor of the nesting class
Member classes:Nesting of classes

Class alpha { };
Class beta { };
Class gamma {
alpha a;
gamma( int x,int y, float z) :
beta b; a(x), b(x,z)
Public: { assignment section ( for
gamma(arglist): a(arglist1), b(arglist2) ordinary other members) }
{ }
};

You might also like