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;
}

INHERITANCE.pptx

  • 1.
  • 2.
    INHERITANCE • Inheritance isthe 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{ // Baseclass 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; Principalp1; t1.numOfStudents = 100; t1.setName(“David John"); p1.setSchool(“Brooklane School"); return 0; }
  • 6.
    Public Inheritance • Anobject 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 BaseClass Derived Access Specifer Accessible from Derived Class Public Access? public Public YES YES protected Protected YES NO private Private NO NO
  • 8.
    Private Inheritance • Withprivate 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 BaseClass Derived Access Specifer Accessible from Derived Class Public Access? public Private YES NO protected Private YES NO private Private NO NO
  • 10.
    Protected Inheritance • Withprotected 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 ofInherited 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 ofInherited 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 • Baseportion 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 namespacestd; 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 << "InstantiatingBase" << endl; Base cBase; cout << "Instantiating Derived" << endl; Derived cDerived; return 0; } • Output:
  • 18.
    Example int main() { cout << "InstantiatingBase" << endl; Base cBase; cout << "Instantiating Derived" << endl; Derived cDerived; return 0; } • Output: Instantiating Base Base Instantiating Derived
  • 19.
    Base and DerivedConstructors • 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 ClassMembers 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: functionin 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 ClassFunctions • 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{ // Baseclass 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 Functionor 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 OverriddenFunction • 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 • Classesused 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 • Onlyone Super Class and Only one Sub Class • One to one Communication between them
  • 31.
    Multilevel Inheritance • Derivedclass can also inherited by another class • Creates a Multiple Levels
  • 32.
    Multiple Inheritances • Aclass inherits the features from two Base Classes
  • 33.
    Hybrid Inheritance • Mixtureof two or More Inheritance and in this Inheritance a Code May Contains two or Three types of inheritance
  • 34.
    Multiple Inheritance • classA // base class A • { • }; • class B // base class B • { • }; • class C : public A, public B // C is derived from A and B • { • };
  • 35.
    Ambiguity in MultipleInheritance 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 problemis 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 • Anotherkind 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 namespacestd; //////////////////////////////////////////////////////////////// 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; }