SlideShare a Scribd company logo
INHERITANCE
INHERITANCE
• Inheritance is the most powerful feature of
Object-Oriented Programming, after classes
themselves.
• Inheritance is the process of creating new
classes, called derived classes, from existing
or base classes.
Revision
• Inheritance - deriving a new class from an
existing class.
– Exisiting or old class: base class (superclass)
– New class: derived class (subclass)
• Re-use classes
• Major aid for structuring the complex
problems
– breaking them into meaningful modular objects
Example
class Teacher{
// Base class
private:
string name;
protected:
int age, numOfStudents;
public:
void setName (string
new_name){
name = new_name; }
void print()
{
Cout<<name;
}
};
class Principal : public Teacher{
// Derived class
private:
string school_name;
int numOfTeachers;
public:
void setSchool(string s_name) {
school_name = s_name; }
void print()
{
Cout<<school_name;
};
int getAge(); {
return age; }
string get_name(){
return name;}
};
Example
int main()
{
Teacher t1;
Principal p1;
t1.numOfStudents = 100;
t1.setName(“David John");
p1.setSchool(“Brooklane School");
return 0;
}
Public Inheritance
• An object of a derived class inherits all the member data and
functions of the base class.
– Public member
• Become public members of the derived class
– Private members
• Not visible in the derived class.
• Derived class may access them via public interface of the base
class.
– Protected Data members
• Visible in the derived class.
• Derived class may access protected members directly.
Public Inheritance
Access
Specifier
In Base Class
Derived Access
Specifer
Accessible from
Derived Class
Public Access?
public Public YES YES
protected Protected YES NO
private Private NO NO
Private Inheritance
• With private inheritance, all members from the base
class are inherited as private.
– Private members stay private
– Protected members become private
– Public members become private
• Note that this does not affect that way that the
derived class accesses members inherited from its
parent! It only affects the code trying to access those
members through the derived class.
Private Inheritance
Access
Specifier
In Base Class
Derived Access
Specifer
Accessible from
Derived Class
Public
Access?
public Private YES NO
protected Private YES NO
private Private NO NO
Protected Inheritance
• With protected inheritance
– Private members stay private
– Protected members stay protected
– Public members become protected
• Used in very particular cases
Access Control - Protected Inheritance
Access
Specifier
In Base Class
Derived Access
Specifer
Accessible from
Derived Class
Public
Access?
public Protected YES NO
protected Protected YES NO
private Private NO NO
Access Level of Inherited Class Members
Class A
Class B: protected A Class C:private A
Private
Protected
Public
Private
Protected
Public
Private
Protected
Public
Obj A
Obj C
Obj B
Can you identify an error here? 12
Access Level of Inherited Class Members
Class A
Class B: protected A Class C:private A
Private
Protected
Public
Private
Protected
Public
Private
Protected
Public
Obj A
Obj C
Obj B
Not Allowed
Not Allowed
13
Constructors & Inheritance
• When C++ constructs
derived objects, it does
so in pieces, starting
with the base portion of
the class.
• Once that is complete,
it then walks through
the inheritance tree and
constructs each derived
portion of the class.
class Base {
public:
int m_nValue;
Base(int nValue=0)
: m_nValue(nValue)
{}
};
class Derived: public Base {
public:
double m_dValue;
Derived(double
dValue=0.0)
: m_dValue(dValue)
{}
};
What Happens
• Base portion of Derived is constructed first.
• Once the Base portion is finished, the Derived
portion is constructed.
• A child can not exist without a parent !
Example
#include <iostream>
using namespace std;
class Base
{
public:
int m_nValue;
Base(int nValue=0)
: m_nValue(nValue)
{
cout << "Base" <<
endl;
}
};
class Derived: public Base
{
public:
double m_dValue;
Derived(double dValue=0.0)
: m_dValue(dValue)
{
cout << "Derived" <<
endl;
}
};
Example
int main()
{
cout <<
"Instantiating Base" <<
endl;
Base cBase;
cout <<
"Instantiating Derived"
<< endl;
Derived cDerived;
return 0;
}
• Output:
Example
int main()
{
cout <<
"Instantiating Base" <<
endl;
Base cBase;
cout <<
"Instantiating Derived"
<< endl;
Derived cDerived;
return 0;
}
• Output:
Instantiating Base
Base
Instantiating Derived
Base and Derived Constructors
• Here’s what actually happens when Derived is instantiated:
– Memory for Derived is set aside (enough for both the Base and
Derived portions) & The appropriate Derived constructor is called
– The Base object is constructed first using the appropriate Base
constructor
– The initialization list initializes variables
– The body of the constructor executes
– Control is returned to the caller
• The Base constructor sets up the Base portion of the object,
control is returned to the Derived constructor, and the
Derived constructor is allowed to finish up it’s job.
Initializing Base Class Members
class Derived: public Base
{
public:
double m_dValue;
Derived(double
dValue=0.0, int nValue=0)
// does not work
: m_dValue(dValue),
m_nValue(nValue)
{
}
};
class Derived: public Base
{
public:
double m_dValue;
Derived(double
dValue=0.0, int nValue=0)
: Base(nValue), //
Call Base(int) constructor
with value nValue!
m_dValue(dValue)
{
}
};
Overriding
• Overriding: function in a derived class that has
the same name and parameter list (usually) as
a function in the base class
• Typically used to replace a function in base
class with different actions in derived class
Overriding Base Class Functions
• overriding != overloading
─with overloading, the parameter lists must be
different
─overloading is about defining a different
functionality of the function with the same name
(e.g. ‘+’ used for adding numbers versus ‘+’ used
for adding matrices)
Example
class Teacher{
// Base class
private:
string name;
int age, numOfStudents;
public:
void setName (const
string & new_name){
name = new_name;
}
void print() const;
};
void Teacher::print()
const
{
cout << "Name: " <<
name<< " Age: " <<
age<< endl;
cout << "Number of
Students: " <<
numOfStudents<< endl;
}
Example
class Principal : public
Teacher{ // Derived
class
string school_name;
int numOfTeachers;
public:
void setSchool(const
string & s_name){
school_name =
s_name;
}
void print() const;
};
void Principal::print()
const
{
// We can write this
only if base class has
protected data members
//cout << "Name: " <<
name << " Age: " << age
<< endl;
//cout << "Number of
Students: " <<
numOfStudents << endl;
cout << "Name of the
school: " << school_name
<< endl;
}
Redefining Member Function or Overriding
print() function of the Principal class overrides (hides) the print() function of
the Teacher class. Now the Principal class has two print() functions.
The function in the base class can be accessed by using the scope resolution
operator (::).
// Print method of Principal class
void Principal::print() const
{
//invoking the print function of the teacher class Teacher::print();
cout << "Name of the school: " << school_name;
}
Access to Overridden Function
• When a function is overridden, all objects of derived class use
the overriding function.
• If necessary to access the overridden version of the function,
it can be done using the scope resolution operator with the
name of the base class and the name of the function:
• BaseClass::FunctionName();
Abstract Class
• Classes used only for deriving other classes
are sometimes called abstract classes,
meaning that no actual instances (objects) of
this class are created.
Constructor& Member functions
• IF no constructor is initialized in the class then
compiler creates instance of class using
default copy constructor.
• Base class constructor is called first.
Types of Inheritance
• Single Inheritance
• Multilevel Inheritance
• Multiple Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance
Single Inheritance
• Only one Super Class and Only one Sub Class
• One to one Communication between them
Multilevel Inheritance
• Derived class can also
inherited by another
class
• Creates a Multiple
Levels
Multiple Inheritances
• A class inherits the
features from two Base
Classes
Hybrid Inheritance
• Mixture of two or More Inheritance and in this
Inheritance a Code May Contains two or Three
types of inheritance
Multiple Inheritance
• class A // base class A
• {
• };
• class B // base class B
• {
• };
• class C : public A, public B // C is derived from A
and B
• {
• };
Ambiguity in Multiple Inheritance
using namespace std;
////////////////////////////////////////////////////////////////
class A
{
public:
void show() { cout << “Class An”; }
};
class B
{
public:
void show() { cout << “Class Bn”; }
};
class C : public A, public B
{
};
////////////////////////////////////////////////////////////////
int main()
{
C objC; //object of class C
// objC.show(); //ambiguous--will not compile
objC.A::show(); //OK
objC.B::show(); //OK
return 0;
}
Solution
• The problem is resolved using the scope-
resolution operator to specify the class in
which the function lies.
• objC.A::show();
• refers to the version of show() that’s in the A
class
• objC.B::show();
• refers to the function in the B class
Ambiguity 2
• Another kind of ambiguity arises if you derive
a class from two classes that are each derived
from the same class. This creates a diamond-
shaped inheritance tree.
Example
#include &ltiostream>
using namespace std;
////////////////////////////////////////////////////////////////
class A
{
public:
void func();
};
class B : public A
{ };
class C : public A
{ };
class D : public B, public C
{ };
////////////////////////////////////////////////////////////////
int main()
{
D objD;
objD.func(); //ambiguous: won’t compile
return 0;
}

More Related Content

Similar to INHERITANCE.pptx

Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
PRIYACHAURASIYA25
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
WaqarRaj1
 
Ganesh groups
Ganesh groupsGanesh groups
Ganesh groups
Ganesh Amirineni
 
Lecturespecial
LecturespecialLecturespecial
Lecturespecial
karan saini
 
OOP
OOPOOP
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdf
AneesAbbasi14
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
Muhammad Hammad Waseem
 
week14 (1).ppt
week14 (1).pptweek14 (1).ppt
week14 (1).ppt
amal68766
 
Inheritance
InheritanceInheritance
Inheritance
zindadili
 
Inheritance
InheritanceInheritance
Inheritance
Munsif Ullah
 
Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03
sivakumarmcs
 
Inheritance and Interfaces
Inheritance and InterfacesInheritance and Interfaces
Inheritance and Interfaces
NAGASURESH MANOHARAN
 
Inheritance
Inheritance Inheritance
Inheritance
sourav verma
 
Inheritance
InheritanceInheritance
Inheritance
poonam.rwalia
 
Inheritance
InheritanceInheritance
2. oop with c++ get 410 day 2
2. oop with c++ get 410   day 22. oop with c++ get 410   day 2
2. oop with c++ get 410 day 2
Mukul kumar Neal
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
PRN USM
 
Inheritance
Inheritance Inheritance
Inheritance
Parthipan Parthi
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
EmanAsem4
 
Inheritance
InheritanceInheritance
Inheritance
abhay singh
 

Similar to INHERITANCE.pptx (20)

Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
lecture 6.pdf
lecture 6.pdflecture 6.pdf
lecture 6.pdf
 
Ganesh groups
Ganesh groupsGanesh groups
Ganesh groups
 
Lecturespecial
LecturespecialLecturespecial
Lecturespecial
 
OOP
OOPOOP
OOP
 
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdf
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
week14 (1).ppt
week14 (1).pptweek14 (1).ppt
week14 (1).ppt
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03Object Oriented Design and Programming Unit-03
Object Oriented Design and Programming Unit-03
 
Inheritance and Interfaces
Inheritance and InterfacesInheritance and Interfaces
Inheritance and Interfaces
 
Inheritance
Inheritance Inheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
Inheritance
InheritanceInheritance
Inheritance
 
2. oop with c++ get 410 day 2
2. oop with c++ get 410   day 22. oop with c++ get 410   day 2
2. oop with c++ get 410 day 2
 
Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1Inheritance & Polymorphism - 1
Inheritance & Polymorphism - 1
 
Inheritance
Inheritance Inheritance
Inheritance
 
02-OOP with Java.ppt
02-OOP with Java.ppt02-OOP with Java.ppt
02-OOP with Java.ppt
 
Inheritance
InheritanceInheritance
Inheritance
 

Recently uploaded

spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
Ratnakar Mikkili
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Christina Lin
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
Rahul
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
PauloRodrigues104553
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
kandramariana6
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
nooriasukmaningtyas
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
mahammadsalmanmech
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
anoopmanoharan2
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
heavyhaig
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
awadeshbabu
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
rpskprasana
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
IJECEIAES
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
IJNSA Journal
 

Recently uploaded (20)

spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
Exception Handling notes in java exception
Exception Handling notes in java exceptionException Handling notes in java exception
Exception Handling notes in java exception
 
International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesHarnessing WebAssembly for Real-time Stateless Streaming Pipelines
Harnessing WebAssembly for Real-time Stateless Streaming Pipelines
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024ACEP Magazine edition 4th launched on 05.06.2024
ACEP Magazine edition 4th launched on 05.06.2024
 
Series of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.pptSeries of visio cisco devices Cisco_Icons.ppt
Series of visio cisco devices Cisco_Icons.ppt
 
132/33KV substation case study Presentation
132/33KV substation case study Presentation132/33KV substation case study Presentation
132/33KV substation case study Presentation
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
Low power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniquesLow power architecture of logic gates using adiabatic techniques
Low power architecture of logic gates using adiabatic techniques
 
Question paper of renewable energy sources
Question paper of renewable energy sourcesQuestion paper of renewable energy sources
Question paper of renewable energy sources
 
PPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testingPPT on GRP pipes manufacturing and testing
PPT on GRP pipes manufacturing and testing
 
Technical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prismsTechnical Drawings introduction to drawing of prisms
Technical Drawings introduction to drawing of prisms
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
[JPP-1] - (JEE 3.0) - Kinematics 1D - 14th May..pdf
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
 
Embedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoringEmbedded machine learning-based road conditions and driving behavior monitoring
Embedded machine learning-based road conditions and driving behavior monitoring
 
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMSA SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
A SYSTEMATIC RISK ASSESSMENT APPROACH FOR SECURING THE SMART IRRIGATION SYSTEMS
 

INHERITANCE.pptx

  • 2. INHERITANCE • Inheritance is the most powerful feature of Object-Oriented Programming, after classes themselves. • Inheritance is the process of creating new classes, called derived classes, from existing or base classes.
  • 3. Revision • Inheritance - deriving a new class from an existing class. – Exisiting or old class: base class (superclass) – New class: derived class (subclass) • Re-use classes • Major aid for structuring the complex problems – breaking them into meaningful modular objects
  • 4. Example class Teacher{ // Base class private: string name; protected: int age, numOfStudents; public: void setName (string new_name){ name = new_name; } void print() { Cout<<name; } }; class Principal : public Teacher{ // Derived class private: string school_name; int numOfTeachers; public: void setSchool(string s_name) { school_name = s_name; } void print() { Cout<<school_name; }; int getAge(); { return age; } string get_name(){ return name;} };
  • 5. Example int main() { Teacher t1; Principal p1; t1.numOfStudents = 100; t1.setName(“David John"); p1.setSchool(“Brooklane School"); return 0; }
  • 6. Public Inheritance • An object of a derived class inherits all the member data and functions of the base class. – Public member • Become public members of the derived class – Private members • Not visible in the derived class. • Derived class may access them via public interface of the base class. – Protected Data members • Visible in the derived class. • Derived class may access protected members directly.
  • 7. Public Inheritance Access Specifier In Base Class Derived Access Specifer Accessible from Derived Class Public Access? public Public YES YES protected Protected YES NO private Private NO NO
  • 8. Private Inheritance • With private inheritance, all members from the base class are inherited as private. – Private members stay private – Protected members become private – Public members become private • Note that this does not affect that way that the derived class accesses members inherited from its parent! It only affects the code trying to access those members through the derived class.
  • 9. Private Inheritance Access Specifier In Base Class Derived Access Specifer Accessible from Derived Class Public Access? public Private YES NO protected Private YES NO private Private NO NO
  • 10. Protected Inheritance • With protected inheritance – Private members stay private – Protected members stay protected – Public members become protected • Used in very particular cases
  • 11. Access Control - Protected Inheritance Access Specifier In Base Class Derived Access Specifer Accessible from Derived Class Public Access? public Protected YES NO protected Protected YES NO private Private NO NO
  • 12. Access Level of Inherited Class Members Class A Class B: protected A Class C:private A Private Protected Public Private Protected Public Private Protected Public Obj A Obj C Obj B Can you identify an error here? 12
  • 13. Access Level of Inherited Class Members Class A Class B: protected A Class C:private A Private Protected Public Private Protected Public Private Protected Public Obj A Obj C Obj B Not Allowed Not Allowed 13
  • 14. Constructors & Inheritance • When C++ constructs derived objects, it does so in pieces, starting with the base portion of the class. • Once that is complete, it then walks through the inheritance tree and constructs each derived portion of the class. class Base { public: int m_nValue; Base(int nValue=0) : m_nValue(nValue) {} }; class Derived: public Base { public: double m_dValue; Derived(double dValue=0.0) : m_dValue(dValue) {} };
  • 15. What Happens • Base portion of Derived is constructed first. • Once the Base portion is finished, the Derived portion is constructed. • A child can not exist without a parent !
  • 16. Example #include <iostream> using namespace std; class Base { public: int m_nValue; Base(int nValue=0) : m_nValue(nValue) { cout << "Base" << endl; } }; class Derived: public Base { public: double m_dValue; Derived(double dValue=0.0) : m_dValue(dValue) { cout << "Derived" << endl; } };
  • 17. Example int main() { cout << "Instantiating Base" << endl; Base cBase; cout << "Instantiating Derived" << endl; Derived cDerived; return 0; } • Output:
  • 18. Example int main() { cout << "Instantiating Base" << endl; Base cBase; cout << "Instantiating Derived" << endl; Derived cDerived; return 0; } • Output: Instantiating Base Base Instantiating Derived
  • 19. Base and Derived Constructors • Here’s what actually happens when Derived is instantiated: – Memory for Derived is set aside (enough for both the Base and Derived portions) & The appropriate Derived constructor is called – The Base object is constructed first using the appropriate Base constructor – The initialization list initializes variables – The body of the constructor executes – Control is returned to the caller • The Base constructor sets up the Base portion of the object, control is returned to the Derived constructor, and the Derived constructor is allowed to finish up it’s job.
  • 20. Initializing Base Class Members class Derived: public Base { public: double m_dValue; Derived(double dValue=0.0, int nValue=0) // does not work : m_dValue(dValue), m_nValue(nValue) { } }; class Derived: public Base { public: double m_dValue; Derived(double dValue=0.0, int nValue=0) : Base(nValue), // Call Base(int) constructor with value nValue! m_dValue(dValue) { } };
  • 21. Overriding • Overriding: function in a derived class that has the same name and parameter list (usually) as a function in the base class • Typically used to replace a function in base class with different actions in derived class
  • 22. Overriding Base Class Functions • overriding != overloading ─with overloading, the parameter lists must be different ─overloading is about defining a different functionality of the function with the same name (e.g. ‘+’ used for adding numbers versus ‘+’ used for adding matrices)
  • 23. Example class Teacher{ // Base class private: string name; int age, numOfStudents; public: void setName (const string & new_name){ name = new_name; } void print() const; }; void Teacher::print() const { cout << "Name: " << name<< " Age: " << age<< endl; cout << "Number of Students: " << numOfStudents<< endl; }
  • 24. Example class Principal : public Teacher{ // Derived class string school_name; int numOfTeachers; public: void setSchool(const string & s_name){ school_name = s_name; } void print() const; }; void Principal::print() const { // We can write this only if base class has protected data members //cout << "Name: " << name << " Age: " << age << endl; //cout << "Number of Students: " << numOfStudents << endl; cout << "Name of the school: " << school_name << endl; }
  • 25. Redefining Member Function or Overriding print() function of the Principal class overrides (hides) the print() function of the Teacher class. Now the Principal class has two print() functions. The function in the base class can be accessed by using the scope resolution operator (::). // Print method of Principal class void Principal::print() const { //invoking the print function of the teacher class Teacher::print(); cout << "Name of the school: " << school_name; }
  • 26. Access to Overridden Function • When a function is overridden, all objects of derived class use the overriding function. • If necessary to access the overridden version of the function, it can be done using the scope resolution operator with the name of the base class and the name of the function: • BaseClass::FunctionName();
  • 27. Abstract Class • Classes used only for deriving other classes are sometimes called abstract classes, meaning that no actual instances (objects) of this class are created.
  • 28. Constructor& Member functions • IF no constructor is initialized in the class then compiler creates instance of class using default copy constructor. • Base class constructor is called first.
  • 29. Types of Inheritance • Single Inheritance • Multilevel Inheritance • Multiple Inheritance • Hierarchical Inheritance • Hybrid Inheritance
  • 30. Single Inheritance • Only one Super Class and Only one Sub Class • One to one Communication between them
  • 31. Multilevel Inheritance • Derived class can also inherited by another class • Creates a Multiple Levels
  • 32. Multiple Inheritances • A class inherits the features from two Base Classes
  • 33. Hybrid Inheritance • Mixture of two or More Inheritance and in this Inheritance a Code May Contains two or Three types of inheritance
  • 34. Multiple Inheritance • class A // base class A • { • }; • class B // base class B • { • }; • class C : public A, public B // C is derived from A and B • { • };
  • 35. Ambiguity in Multiple Inheritance using namespace std; //////////////////////////////////////////////////////////////// class A { public: void show() { cout << “Class An”; } }; class B { public: void show() { cout << “Class Bn”; } }; class C : public A, public B { }; //////////////////////////////////////////////////////////////// int main() { C objC; //object of class C // objC.show(); //ambiguous--will not compile objC.A::show(); //OK objC.B::show(); //OK return 0; }
  • 36. Solution • The problem is resolved using the scope- resolution operator to specify the class in which the function lies. • objC.A::show(); • refers to the version of show() that’s in the A class • objC.B::show(); • refers to the function in the B class
  • 37. Ambiguity 2 • Another kind of ambiguity arises if you derive a class from two classes that are each derived from the same class. This creates a diamond- shaped inheritance tree.
  • 38. Example #include &ltiostream> using namespace std; //////////////////////////////////////////////////////////////// class A { public: void func(); }; class B : public A { }; class C : public A { }; class D : public B, public C { }; //////////////////////////////////////////////////////////////// int main() { D objD; objD.func(); //ambiguous: won’t compile return 0; }