0% found this document useful (0 votes)
40 views

Inheritance

Notes about inheritance in c++

Uploaded by

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

Inheritance

Notes about inheritance in c++

Uploaded by

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

Inheritance

Introduction
 Reusability--building new components by utilizing existing components-
is yet another important aspect of OO paradigm.
 It is always good/ “productive” if we are able to reuse something that is
already exists rather than creating the same all over again.
 This is achieve by creating new classes, reusing the properties of existing
classes.
It saves money , time, efforts etc.
Definition
• This mechanism of deriving a new class from existing/old
class is called “inheritance”.
• The old class is known as “base” class, “super” class or
“parent” class.
• The new class is known as “sub” class, “derived” class, or
“child” class.
• Example:

EMPLOYEE

NONTEACHING TEACHING SECURITY

FULL TIME PART TIME


Defining Derived classes

• Syntax:
class DerivedClassName : access-level BaseClassName
where
– access-level specifies the type of derivation
• private by default, or
• Public
• Protected

• Any class can serve as a base class


– Thus a derived class can also be a base class
Implementing Inheritance in C++ by Deriving Classes From the Base Class
• Syntax:
class base_classname
{

};
class derived_classname : <access-specifier>base_classname
{
...
};
class derived:public base
#include<iostream>
{
using namespace std;
int num3;
class base
public:
{
void get()
int num1;
{
public:
num2=30;
int num2;
num3=40;
void getdata()
}
{ int main()
void disp()
num1=10;
num2=20;
{ {
cout<<num2<<" "; derived d;
}
cout<<num3<<endl;
void display() d.getdata();
}
{ d.display();
};
cout<<num1<<" "; d.get();
cout<<num2<<endl;
}
d.disp();
}; return 0;
}
Types of Inheritance

1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance
Examples
class ABC : private XYZ //private derivation
{
Members of ABC
};

class ABC : public XYZ //public derivation


{
Members of ABC
};

class ABC : protected XYZ //protected derivation


{
Members of ABC
};

class ABC : XYZ //private derivation by default


{
Members of ABC
Public inheritance

• When a base class is publicly inherited, ‘public


members’ of the base class become ‘public
members’ of the derived class and therefore they
are accessible to the objects of the derived class.
• Note: private members of the base class are not
accessible in the derived class (to preserve
encapsulation)
Private inheritance

• Public members of base class become private


members of derived class
• Protected 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.
• They are inaccessible to the objects of the derived
class.
Protected inheritance

• A member declared as protected is accessible by


the member functions within its class and any class
immediately derived from it.
• It cannot be accessed by the functions outside
these two classes.
• It is possible to inherit a base class in protected
mode. In this, Public and protected members of the
base class become protected members of the
derived class.
class B:protected A
#include<iostream> {
using namespace std; protected:
class A int y;
public:
{
void get(int n)
protected: {
int x; int main()
y=n;
public: getdata(8); {
void getdata(int m) } B b1;
{ void put() b1.get(10);
{ b1.put();
x=m; cout<<y<<" ";
} b1.sum();
putdata();
void putdata() } return 0;
{ void sum() }
{
cout<<x<<" ";
int z=x+y;
} cout<<"sum="<<z;
}; }
};
Private: // visible to member function within class//

Protected: // visible to member functions of its own


and immediate derived class//

Public: // visible to all functions in the program//


Class B
Private Not Inheritable
Protected

Public

Class D1:public B ClassD2:private B

Private Private

Protected Protected

Public Public

Class X:public D1,protected D2

Private

Protected

Public
Access Rights of Derived Classes
Type of Inheritance

Private Protected Public


for Members
Access Control

inheritance inheritance inheritance


private Not inherited Not inherited Not inherited
protected Private protected protected
public private protected public
• The type of inheritance defines the access level for the
members of derived class that are inherited from the base
class
Understanding Inheritance Restrictions

• The following are never inherited:


– constructors
– destructors
– friend functions
– overloaded new operators
– overloaded = operators
• Class friendship is not inherited
Adding members “Publicly & Privately”

Public Inheritance Private Inheritance


Multiple Inheritance
• Is the phenomenon where a class may inherit
from two or more classes
• Syntax:
class derived : public base1, public base2
{
//Body of class
}; M N

• Base classes are separated by comma


P
Multiple Inheritance
#include <iostream>
Using namespace std; void P::display()
class M
{
{
protected: cout<<“m=“<<m<<“\n”;
int m; cout<<“n=“<<n<<“\n”;
public: cout<<“m*n=”<<m*n<<“\n”;
void get_m(int x) }
{ m=x; } int main()
};
class N {
{
P p;
protected:
int n; p.get_m(10); //m=10
public:
void get_n(int y) p.get_n(20); //n=20
{ n= y;}
}; p.display(); //m*n = 200
class P:public M, public N return 0;
{ public:
void display(); }
};
Multilevel Inheritance
• It is also possible to derive a class from an existing
derived class.
• It is implemented by defining atleast three classes.
• Each derived class must have a kind of relationship
with its immediate base class.
A

C
Multilevel Inheritance
class test : public student
#include <iostream> {
using namespace std; protected:
class student float sub1,sub2;
{ public:
protected: void get_marks(float x, float y)
int roll_no; { sub1=x; sub2=y; }
public: void put_marks()
void get_no(int a) { cout<<“Marks in sub1”<<sub1<<endl;
{ roll_no=a; } cout<<“Marks in sub2”<<sub2<<endl;
}
void put_no()
};
{ class result:public test
cout<<“Roll number is”<<roll_no;
} { float total ;
}; public:
void display() ;
};
void result:: display()
{
total= sub1+sub2;
put_no(); //function of class student
put_marks(); //function of class test
cout<<“total = “<<total;
}
int main()
{
result student1;
student1.get_no(102);
student1.get_marks(80.0,98.5);
student1.display();
return 0;
}
Overriding Parent Class Functions
• When any class member function is called, the
following steps take place:
1. The compiler looks for a matching function in the class
of the object using the function name
2. If no match is found in this class, the compiler looks for a
matching function in the parent class
3. If no match is found in the parent class, the compiler
continues up the inheritance hierarchy, looking at the
parent of the parent, until the base class is reached
4. If no match is found in any class, an error message is
issued
25
#include <iostream>

using namespace std; int main()


class BaseClass {
{ DerivedClass obj ;
public:
obj.show();
void show()
{ return 0;
cout<<"Function of Parent Class"; }
}
};
class DerivedClass: public BaseClass
{
public:
void show()
{
cout<<"Function of Child Class";
}
Ambiguity in Multiple Inheritance
• Can arise when two base classes contain a function of the
same name
Example:

M N

P
class M class P:public M,public N
{ {
public: public:
void display() void show()
{
{
cout<<"in class M";
cout<<"in class P";
}
}; }
};
class N
{
public:
void display() int main()
{ {
cout<<"in class N"; P ob;
} ob.show();
}; ob.display();
return 0;
}
• Can be resolved
– By overriding the function in the derived class
int main()
{
P ob;
ob.M::display();
ob.N::display();
return 0;
}
• Ambiguity in Single Inheritance
int main()
class A {
{ B b;
public: b.display();
void display()
{ return 0;
cout<<“A\n”;
}
}
};
class B: public A
{
public:
void display()
{
cout<<“B\n”;
In this case, the function in
}
the derived class overrides
};
the inherited function.
Can be resolved:
– By using the scope resolution operator
int main()
{
B b;
b.A::display();
b.B::display();
}
Hybrid Inheritance

Record

Marks Avg

Result
Virtual base class

Student

Test score

result

//Multiple copies of the variables of


student class are generated
Virtual base class
class A
{…….
A ………
};
B1 B2 class B1:virtual public A
{…….
…….
C };
class B2:public virtual A
{…….
……..
};
class C:public B1,public B2
{………
………
}; //only one copy of A
will be inherited
Virtual base class

class student class test : virtual public student


{ {
protected: protected:
int rollno; int mark1,mark2;
public: public:
void getroll() void getmarks()
{ {
cout<<"enter roll no"; cout<<"enter the marks of subjects";
cin>>rollno; cin>>mark1>>mark2;
} }
void putroll() void putmarks()
{ {
cout<<rollno; cout<<mark1<<mark2;
} }
}; };
void result::sum()
class sports: public virtual student {
{ protected : total=mark1+mark2+score;
int score; cout<<"rollno"<<rollno<<"\n";
public: cout<<"mark1"<<mark1<<"\n";
void getscore() cout<<"mark2"<<mark2<<"\n";
{ cout<<“score is"<<score<<"\n";
cout<<"enter the marks in sports"; cout<<"total is"<<total;
cin>>score; } }
void putscore()
{ cout<<score;
} };
class result : public test , public sports int main()
{ {
int total;
public: result r1;
void sum(); r1.getroll();
}; r1.getmarks();
r1.getscore();
r1.sum();
Abstract Class
• An abstract class is one that is not used to create
objects.
• An abstract class is designed only to act as a base
class i.e. 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. class sample
{
int x,y;
public:
virtual void show()=0;
}
Constructors and Inheritance

• If a base class constructor takes no arguments, the derived


class need not to have constructor function.
• If any base class contain 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.
• When both the derived and base classes contain constructor,
the base class constructor is executed first and then the
constructor in the derived class is executed.
Order of Constructors and destructors in
derived classes
• Derived-class constructor
– Calls the constructor for its base class first to initialize its base-
class members
– If the derived-class constructor is omitted, its default constructor
calls the base-class’ default constructor
• Destructors are called in the reverse order of
constructor calls.
– Derived-class destructor is called before its base-class destructor
Constructors in Derived Class
• The general form of defining a derived constructor is :

Der_constructor(par_list) : base1(par_list1), base2(par_list2)


{
// implementation of derived class constructor
}
Here Der_constructor is the name of derived class constructor
and par_list specifies the list of parameters that the derived
class constructor will receive, out of which some may be used
to initialize its own data members whereas remaining ones
may be passed to its base class constructors.
Initialization list starts with colon(:) and consists of calls to
base class constructors where each call is separated by
comma.
Example

• Derived class object created as:

• Definition of constructor called:


Order of Constructors in derived classes
Class B:public A
{ //A() base constructor
}; //B() derived constructor

Class A:public B, public C


{ //B() base first
}; //C() base second
//A() derived
Class A:public B, virtual C
{ //C() virtual base
};
//B() ordinary base
//A() derived
Constructors in derived classes
#include <iostream> class gamma:public beta, public alpha
class alpha {
{ int m,n;
int x; public:
public: alpha(int i) gamma(int a, float b,int c, int d) :alpha(a), beta(b)
{ x=i; {
cout<<“alpha initialized”; } m=c;
void show_x() n=d;
{ cout<<“x=“<<x;} cout<<“gamma initialized”;
}; }
class beta void show_mn(void)
{ float y; {
public: beta(float j) cout<<“m=“<<m;
{ y=j; cout<<“n=“<<n;
cout<<“beta initialized”;} }
void show_y() };
{
cout<<“y=“<<y; }
};
Constructors in derived classes
int main()
{
gamma g(5,12.34,50,20); Output:
g.show_x(); beta initialized
g.show_y(); alpha initialized
g.show_mn(); gamma initialized
return 0;
} x=5
y=12.34
m=50
n=20
Aggregation
Here object of one class is declared as member of another class

class Date
class student
{ Object of
{ Date class
private:
private:
int month, day, year;
int id_no;
public:
Constructor is Date dob;
Date(int m, int d, int y) called public:
{
student(int id, int d, int m, int y)
month = m; : dob(d,m,y)
day = d; {
year= y; id_no = id;
} }
}; };
Object Slicing

When a derived class object is assigned to a base


class object.

only base class data will be copied from derived


class and derived data will be sliced. This will occur
in C++.
• When a Derived Class object is assigned to
Base class, the base class' contents in the
derived object are copied to the base class
leaving behind the derived class specific
contents. This is referred as Object Slicing.
That is, the base class object can access only
the base class members. This also implies the
separation of base class members from
derived class members has happened.

Object Slicing
Base & Derived class
Main() function
class base
int main()
{
{
public:
base b;
int i, j;
derived d; Derived class
}; members are
b=d; copies one-by-one
} into base class
class derived: public base
{
public:
int k;
};
Object Slicing (cont.)

class base class derived: public base


{ {
public: public:
int i; int i;
copied
int j; int j;
}; int k;
};
Gets sliced. Means on
copied to anything
Object slice prevention

• Object slicing can be prevented by making the base


class pure virtual, so that base instance will not be
allowed.(It is not possible to create the object of a
class which contains a pure virtual method.)
• Object slicing can't occurr, if pointers or reference
to the objects used, as both pointers of the same
size.
#include<iostream> int main()
using namespace std;
class base {
{ base b;
public: derived d;
int x; cout<<"size of base class is "<<sizeof(b);
base() cout<<"size of derive class is"<< sizeof(d);
{
x = 10; b=d;
} cout<<"size of b class is "<<sizeof(b);
}; }
class derived: public base
{
public: Output:
int y; size of base class is 4
derived()
{ size of derive class is 8
y=20;
size of b class is 4
x=30;
}
};
Object Delegation

• It is behaviour of object in terms of another object.


• Alternative to class inheritance.
• Here, 2 objects are involved in handling request:
– A receiving object delegates operations to its delegate.
• It is analogous to child classes sending request to
parent classes.
Example
A class object
declared

Constructor

Function of class A
called to perform
task

Object of class A
passed in constructor
Inheritance(egAggration concepts,
The const keyword)
• Const argument-
– Int student(const section *s);
• Const member function- the functions wont
change any value in the function. The compiler will
generate the error if functions tries to alter the data.
• Void mul(int, int) const; //declaration
• Void mul(int a, int v) const //definition
{
...;
}
class ABC
{
public:
int a; int main()
void func() {
{ ABC ob;
a=99; ob.func();
} cout<<ob.a;
void confunc() const ob.confunc();
{ cout<<ob.a;
a=100; //error cant modify a member. return 0;
} }
};
• Const object
syntax
const classname objectname;
eg: const student s1;
• Const object calls only const member functions.

You might also like