SlideShare a Scribd company logo
1 of 28
1
class Rectangle{
private:
int numVertices;
float *xCoord, *yCoord;
public:
void set(float *x, float *y, int nV);
float area();
};
Inheritance Concept
Rectangle
Triangle
Polygon
class Polygon{
private:
int numVertices;
float *xCoord, *yCoord;
public:
void set(float *x, float *y, int nV);
};
class Triangle{
private:
int numVertices;
float *xCoord, *yCoord;
public:
void set(float *x, float *y, int nV);
float area();
};
2
Rectangle
Triangle
Polygon
class Polygon{
protected:
int numVertices;
float *xCoord, float *yCoord;
public:
void set(float *x, float *y, int nV);
};
class Rectangle : public Polygon{
public:
float area();
};
class Rectangle{
protected:
int numVertices;
float *xCoord, float *yCoord;
public:
void set(float *x, float *y, int nV);
float area();
};
Inheritance Concept
3
Rectangle
Triangle
Polygon
class Polygon{
protected:
int numVertices;
float *xCoord, float *yCoord;
public:
void set(float *x, float *y, int nV);
};
class Triangle : public Polygon{
public:
float area();
};
class Triangle{
protected:
int numVertices;
float *xCoord, float *yCoord;
public:
void set(float *x, float *y, int nV);
float area();
};
Inheritance Concept
4
Inheritance Concept
Point
Circle 3D-Point
class Point{
protected:
int x, y;
public:
void set (int a, int b);
};
class Circle : public Point{
private:
double r;
};
class 3D-Point: public Point{
private:
int z;
};
x
y
x
y
r
x
y
z
5
• Augmenting the original class
• Specializing the original class
Inheritance Concept
RealNumber
ComplexNumber
ImaginaryNumber
Rectangle
Triangle
Polygon Point
Circle
real
imag
real imag
3D-Point
6
Why Inheritance ?
Inheritance is a mechanism for
• building class types from existing class types
• defining new class types to be a
–specialization
–augmentation
of existing types
7
Define a Class Hierarchy
• Syntax:
class DerivedClassName : access-level BaseClassName
where
– access-level specifies the type of derivation
• private by default, or
• public
• Any class can serve as a base class
– Thus a derived class can also be a base class
8
Class Derivation
Point
3D-Point
class Point{
protected:
int x, y;
public:
void set (int a, int b);
};
class 3D-Point : public Point{
private:
double z;
… …
};
class Sphere : public 3D-Point{
private:
double r;
… …
};
Sphere
Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere
9
What to inherit?
• In principle, every member of a base class is
inherited by a derived class
– just with different access permission
10
Access Control Over the Members
• Two levels of access control
over class members
– class definition
– inheritance type
base class/ superclass/
parent class
derived class/ subclass/
child class
derivefrom
membersgoesto
class Point{
protected: int x, y;
public: void set(int a, int b);
};
class Circle : public Point{
… …
};
11
• The type of inheritance defines the access level for the
members of derived class that are inherited from the base
class
Access Rights of Derived Classes
private protected public
private - - -
protected private protected protected
public private protected public
Type of Inheritance
AccessControl
forMembers
12
class daughter : --------- mother{
private: double dPriv;
public: void mFoo ( );
};
Class Derivation
class mother{
protected: int mProc;
public: int mPubl;
private: int mPriv;
};
class daughter : --------- mother{
private: double dPriv;
public: void dFoo ( );
};
void daughter :: dFoo ( ){
mPriv = 10; //error
mProc = 20;
};
private/protected/public
int main() {
/*….*/
}
class grandDaughter : public daughter {
private: double gPriv;
public: void gFoo ( );
};
13
What to inherit?
• In principle, every member of a base class is
inherited by a derived class
– just with different access permission
• However, there are exceptions for
– constructor and destructor
– operator=() member
– friends
Since all these functions are class-specific
14
Constructor Rules for Derived Classes
The default constructor and the destructor of the
base class are always called when a new object
of a derived class is created or destroyed.
class A {
public:
A ( )
{cout<< “A:default”<<endl;}
A (int a)
{cout<<“A:parameter”<<endl;}
};
class B : public A
{
public:
B (int a)
{cout<<“B”<<endl;}
};
B test(1);
A:default
B
output:
15
Constructor Rules for Derived Classes
You can also specify an constructor of the
base class other than the default constructor
class A {
public:
A ( )
{cout<< “A:default”<<endl;}
A (int a)
{cout<<“A:parameter”<<endl;}
};
class C : public A {
public:
C (int a) : A(a)
{cout<<“C”<<endl;}
};
C test(1);
A:parameter
C
output:
DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass
args )
{ DerivedClass constructor body }
16
Define its Own Members
Point
Circle
class Point{
protected:
int x, y;
public:
void set(int a, int b);
};
class Circle : public Point{
private:
double r;
public:
void set_r(double c);
};
x
y
x
y
r
class Circle{
protected:
int x, y;
private:
double r;
public:
void set(int a, int b);
void set_r(double c);
};
The derived class can also define
its own members, in addition to
the members inherited from the
base class
17
Even more …
• A derived class can override methods defined in its parent
class. With overriding,
– the method in the subclass has the identical signature to the method
in the base class.
– a subclass implements its own version of a base class method.
class A {
protected:
int x, y;
public:
void print ()
{cout<<“From A”<<endl;}
};
class B : public A {
public:
void print ()
{cout<<“From B”<<endl;}
};
18
class Point{
protected:
int x, y;
public:
void set(int a, int b)
{x=a; y=b;}
void foo ();
void print();
};
class Circle : public Point{
private: double r;
public:
void set (int a, int b, double c) {
Point :: set(a, b); //same name function call
r = c;
}
void print(); };
Access a Method
Circle C;
C.set(10,10,100); // from class Circle
C.foo (); // from base class Point
C.print(); // from class Circle
Point A;
A.set(30,50); // from base class Point
A.print(); // from base class Point
19
Putting Them Together
• Time is the base class
• ExtTime is the derived class with
public inheritance
• The derived class can
– inherit all members from the base
class, except the constructor
– access all public and protected
members of the base class
– define its private data member
– provide its own constructor
– define its public member functions
– override functions inherited from
the base class
ExtTime
Time
20
class Time Specification
class Time{
public :
void Set ( int h, int m, int s ) ;
void Increment ( ) ;
void Write ( ) const ;
Time ( int initH, int initM, int initS ) ; // constructor
Time ( ) ; // default constructor
protected :
int hrs ;
int mins ;
int secs ;
} ;
// SPECIFICATION FILE ( time.h)
21
Class Interface Diagram
Protected data:
hrs
mins
secs
Set
Increment
Write
Time
Time
Time class
22
Derived Class ExtTime
// SPECIFICATION FILE ( exttime.h)
#include “time.h”
enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT } ;
class ExtTime : public Time
// Time is the base class and use public inheritance
{
public :
void Set ( int h, int m, int s, ZoneType timeZone ) ;
void Write ( ) const; //overridden
ExtTime (int initH, int initM, int initS, ZoneType initZone ) ;
ExtTime (); // default constructor
private :
ZoneType zone ; // added data member
} ;
23
Class Interface Diagram
Protected data:
hrs
mins
secs
ExtTime class
Set
Increment
Write
Time
Time
Set
Increment
Write
ExtTime
ExtTime
Private data:
zone
24
Implementation of ExtTime
Default Constructor
ExtTime :: ExtTime ( )
{
zone = EST ;
}
The default constructor of
base class, Time(), is
automatically called, when an
ExtTime object is created.
ExtTime et1;
hrs = 0
mins = 0
secs = 0
zone = EST
et1
25
Implementation of ExtTime
Another Constructor
ExtTime :: ExtTime (int initH, int initM, int initS, ZoneType initZone)
: Time (initH, initM, initS)
// constructor initializer
{
zone = initZone ;
}
ExtTime *et2 =
new ExtTime(8,30,0,EST);
hrs = 8
mins = 30
secs = 0
zone = EST
et2
5000
???
6000
5000
26
Implementation of ExtTime
void ExtTime :: Set (int h, int m, int s, ZoneType timeZone)
{
Time :: Set (hours, minutes, seconds); // same name function call
zone = timeZone ;
}
void ExtTime :: Write ( ) const // function overriding
{
string zoneString[8] =
{“EST”, “CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT”} ;
Time :: Write ( ) ;
cout <<‘ ‘<<zoneString[zone]<<endl;
}
27
Working with ExtTime
#include “exttime.h”
… …
int main()
{
ExtTime thisTime ( 8, 35, 0, PST ) ;
ExtTime thatTime ; // default constructor called
thatTime.Write( ) ; // outputs 00:00:00 EST
thatTime.Set (16, 49, 23, CDT) ;
thatTime.Write( ) ; // outputs 16:49:23 CDT
thisTime.Increment ( ) ;
thisTime.Increment ( ) ;
thisTime.Write ( ) ; // outputs 08:35:02 PST
}
28
Take Home Message
• Inheritance is a mechanism for defining new
class types to be a specialization or an
augmentation of existing types.
• In principle, every member of a base class is
inherited by a derived class with different
access permissions, except for the constructors

More Related Content

What's hot

ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyondFrancis Johny
 
Torturing the PHP interpreter
Torturing the PHP interpreterTorturing the PHP interpreter
Torturing the PHP interpreterLogicaltrust pl
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعةجامعة القدس المفتوحة
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثةشرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثةجامعة القدس المفتوحة
 
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingRoberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingDemetrio Siragusa
 
AP Derivatives
AP DerivativesAP Derivatives
AP Derivativestschmucker
 
ASFWS 2012 - Hash-flooding DoS reloaded: attacks and defenses par Jean-Philip...
ASFWS 2012 - Hash-flooding DoS reloaded: attacks and defenses par Jean-Philip...ASFWS 2012 - Hash-flooding DoS reloaded: attacks and defenses par Jean-Philip...
ASFWS 2012 - Hash-flooding DoS reloaded: attacks and defenses par Jean-Philip...Cyber Security Alliance
 
Pybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonPybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonChristoph Matthies
 
Oxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcesOxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcescorehard_by
 
Types, Operators and Primitives
Types, Operators and PrimitivesTypes, Operators and Primitives
Types, Operators and Primitivesalexisabril
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)PROIDEA
 
Introducing AlloyUI DiagramBuilder
Introducing AlloyUI DiagramBuilderIntroducing AlloyUI DiagramBuilder
Introducing AlloyUI DiagramBuilderEduardo Lundgren
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matterDawid Weiss
 
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012YUI3 and AlloyUI Introduction for Pernambuco.JS 2012
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012Eduardo Lundgren
 

What's hot (20)

ECMAScript 6 and beyond
ECMAScript 6 and beyondECMAScript 6 and beyond
ECMAScript 6 and beyond
 
Torturing the PHP interpreter
Torturing the PHP interpreterTorturing the PHP interpreter
Torturing the PHP interpreter
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعةشرح مقرر البرمجة 2   لغة جافا - الوحدة الرابعة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الرابعة
 
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثةشرح مقرر البرمجة 2   لغة جافا - الوحدة الثالثة
شرح مقرر البرمجة 2 لغة جافا - الوحدة الثالثة
 
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + ProcessingRoberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
Roberto Gallea: Workshop Arduino, giorno #2 Arduino + Processing
 
AP Derivatives
AP DerivativesAP Derivatives
AP Derivatives
 
ASFWS 2012 - Hash-flooding DoS reloaded: attacks and defenses par Jean-Philip...
ASFWS 2012 - Hash-flooding DoS reloaded: attacks and defenses par Jean-Philip...ASFWS 2012 - Hash-flooding DoS reloaded: attacks and defenses par Jean-Philip...
ASFWS 2012 - Hash-flooding DoS reloaded: attacks and defenses par Jean-Philip...
 
662305 10
662305 10662305 10
662305 10
 
Pybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in PythonPybelsberg — Constraint-based Programming in Python
Pybelsberg — Constraint-based Programming in Python
 
Sbaw091110
Sbaw091110Sbaw091110
Sbaw091110
 
Oxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resourcesOxygine 2 d objects,events,debug and resources
Oxygine 2 d objects,events,debug and resources
 
Polynomial
PolynomialPolynomial
Polynomial
 
YUI Tidbits
YUI TidbitsYUI Tidbits
YUI Tidbits
 
Types, Operators and Primitives
Types, Operators and PrimitivesTypes, Operators and Primitives
Types, Operators and Primitives
 
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
4Developers 2018: Ile (nie) wiesz o strukturach w .NET (Łukasz Pyrzyk)
 
Introducing AlloyUI DiagramBuilder
Introducing AlloyUI DiagramBuilderIntroducing AlloyUI DiagramBuilder
Introducing AlloyUI DiagramBuilder
 
Property-based testing
Property-based testingProperty-based testing
Property-based testing
 
sizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may mattersizeof(Object): how much memory objects take on JVMs and when this may matter
sizeof(Object): how much memory objects take on JVMs and when this may matter
 
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012YUI3 and AlloyUI Introduction for Pernambuco.JS 2012
YUI3 and AlloyUI Introduction for Pernambuco.JS 2012
 
C++ L09-Classes Part2
C++ L09-Classes Part2C++ L09-Classes Part2
C++ L09-Classes Part2
 

Similar to C++ Inheritance Concept Explained with Examples

Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.pptinstaface
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining ClassesIntro C# Book
 
Inheritance
InheritanceInheritance
InheritanceTech_MX
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...MaruMengesha
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewPaulo Morgado
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarROHIT JAISWAR
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoopVladislav Hadzhiyski
 
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdfAneesAbbasi14
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#Svetlin Nakov
 
Review constdestr
Review constdestrReview constdestr
Review constdestrrajudasraju
 

Similar to C++ Inheritance Concept Explained with Examples (20)

Inheritance.pptx
Inheritance.pptxInheritance.pptx
Inheritance.pptx
 
Inheritance in C++.ppt
Inheritance in C++.pptInheritance in C++.ppt
Inheritance in C++.ppt
 
Inheritance
InheritanceInheritance
Inheritance
 
14. Defining Classes
14. Defining Classes14. Defining Classes
14. Defining Classes
 
Closer look at classes
Closer look at classesCloser look at classes
Closer look at classes
 
Inheritance
InheritanceInheritance
Inheritance
 
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...
WINSEM2020-21_STS3105_SS_VL2020210500169_Reference_Material_I_03-Mar-2021_L13...
 
C# 6.0 - April 2014 preview
C# 6.0 - April 2014 previewC# 6.0 - April 2014 preview
C# 6.0 - April 2014 preview
 
Java programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswarJava programming lab_manual_by_rohit_jaiswar
Java programming lab_manual_by_rohit_jaiswar
 
03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop03 classes interfaces_principlesofoop
03 classes interfaces_principlesofoop
 
[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance[OOP - Lec 20,21] Inheritance
[OOP - Lec 20,21] Inheritance
 
lecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdflecture-2021inheritance-160705095417.pdf
lecture-2021inheritance-160705095417.pdf
 
Lab3
Lab3Lab3
Lab3
 
Object-Oriented Programming with C#
Object-Oriented Programming with C#Object-Oriented Programming with C#
Object-Oriented Programming with C#
 
7 class objects
7 class objects7 class objects
7 class objects
 
inhertance c++
inhertance c++inhertance c++
inhertance c++
 
Review constdestr
Review constdestrReview constdestr
Review constdestr
 
Review constdestr
Review constdestrReview constdestr
Review constdestr
 
Object-oriented Basics
Object-oriented BasicsObject-oriented Basics
Object-oriented Basics
 
C++ oop
C++ oopC++ oop
C++ oop
 

Recently uploaded

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 

Recently uploaded (20)

Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 

C++ Inheritance Concept Explained with Examples

  • 1. 1 class Rectangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept Rectangle Triangle Polygon class Polygon{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); }; class Triangle{ private: int numVertices; float *xCoord, *yCoord; public: void set(float *x, float *y, int nV); float area(); };
  • 2. 2 Rectangle Triangle Polygon class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; class Rectangle : public Polygon{ public: float area(); }; class Rectangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept
  • 3. 3 Rectangle Triangle Polygon class Polygon{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); }; class Triangle : public Polygon{ public: float area(); }; class Triangle{ protected: int numVertices; float *xCoord, float *yCoord; public: void set(float *x, float *y, int nV); float area(); }; Inheritance Concept
  • 4. 4 Inheritance Concept Point Circle 3D-Point class Point{ protected: int x, y; public: void set (int a, int b); }; class Circle : public Point{ private: double r; }; class 3D-Point: public Point{ private: int z; }; x y x y r x y z
  • 5. 5 • Augmenting the original class • Specializing the original class Inheritance Concept RealNumber ComplexNumber ImaginaryNumber Rectangle Triangle Polygon Point Circle real imag real imag 3D-Point
  • 6. 6 Why Inheritance ? Inheritance is a mechanism for • building class types from existing class types • defining new class types to be a –specialization –augmentation of existing types
  • 7. 7 Define a Class Hierarchy • Syntax: class DerivedClassName : access-level BaseClassName where – access-level specifies the type of derivation • private by default, or • public • Any class can serve as a base class – Thus a derived class can also be a base class
  • 8. 8 Class Derivation Point 3D-Point class Point{ protected: int x, y; public: void set (int a, int b); }; class 3D-Point : public Point{ private: double z; … … }; class Sphere : public 3D-Point{ private: double r; … … }; Sphere Point is the base class of 3D-Point, while 3D-Point is the base class of Sphere
  • 9. 9 What to inherit? • In principle, every member of a base class is inherited by a derived class – just with different access permission
  • 10. 10 Access Control Over the Members • Two levels of access control over class members – class definition – inheritance type base class/ superclass/ parent class derived class/ subclass/ child class derivefrom membersgoesto class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ … … };
  • 11. 11 • The type of inheritance defines the access level for the members of derived class that are inherited from the base class Access Rights of Derived Classes private protected public private - - - protected private protected protected public private protected public Type of Inheritance AccessControl forMembers
  • 12. 12 class daughter : --------- mother{ private: double dPriv; public: void mFoo ( ); }; Class Derivation class mother{ protected: int mProc; public: int mPubl; private: int mPriv; }; class daughter : --------- mother{ private: double dPriv; public: void dFoo ( ); }; void daughter :: dFoo ( ){ mPriv = 10; //error mProc = 20; }; private/protected/public int main() { /*….*/ } class grandDaughter : public daughter { private: double gPriv; public: void gFoo ( ); };
  • 13. 13 What to inherit? • In principle, every member of a base class is inherited by a derived class – just with different access permission • However, there are exceptions for – constructor and destructor – operator=() member – friends Since all these functions are class-specific
  • 14. 14 Constructor Rules for Derived Classes The default constructor and the destructor of the base class are always called when a new object of a derived class is created or destroyed. class A { public: A ( ) {cout<< “A:default”<<endl;} A (int a) {cout<<“A:parameter”<<endl;} }; class B : public A { public: B (int a) {cout<<“B”<<endl;} }; B test(1); A:default B output:
  • 15. 15 Constructor Rules for Derived Classes You can also specify an constructor of the base class other than the default constructor class A { public: A ( ) {cout<< “A:default”<<endl;} A (int a) {cout<<“A:parameter”<<endl;} }; class C : public A { public: C (int a) : A(a) {cout<<“C”<<endl;} }; C test(1); A:parameter C output: DerivedClassCon ( derivedClass args ) : BaseClassCon ( baseClass args ) { DerivedClass constructor body }
  • 16. 16 Define its Own Members Point Circle class Point{ protected: int x, y; public: void set(int a, int b); }; class Circle : public Point{ private: double r; public: void set_r(double c); }; x y x y r class Circle{ protected: int x, y; private: double r; public: void set(int a, int b); void set_r(double c); }; The derived class can also define its own members, in addition to the members inherited from the base class
  • 17. 17 Even more … • A derived class can override methods defined in its parent class. With overriding, – the method in the subclass has the identical signature to the method in the base class. – a subclass implements its own version of a base class method. class A { protected: int x, y; public: void print () {cout<<“From A”<<endl;} }; class B : public A { public: void print () {cout<<“From B”<<endl;} };
  • 18. 18 class Point{ protected: int x, y; public: void set(int a, int b) {x=a; y=b;} void foo (); void print(); }; class Circle : public Point{ private: double r; public: void set (int a, int b, double c) { Point :: set(a, b); //same name function call r = c; } void print(); }; Access a Method Circle C; C.set(10,10,100); // from class Circle C.foo (); // from base class Point C.print(); // from class Circle Point A; A.set(30,50); // from base class Point A.print(); // from base class Point
  • 19. 19 Putting Them Together • Time is the base class • ExtTime is the derived class with public inheritance • The derived class can – inherit all members from the base class, except the constructor – access all public and protected members of the base class – define its private data member – provide its own constructor – define its public member functions – override functions inherited from the base class ExtTime Time
  • 20. 20 class Time Specification class Time{ public : void Set ( int h, int m, int s ) ; void Increment ( ) ; void Write ( ) const ; Time ( int initH, int initM, int initS ) ; // constructor Time ( ) ; // default constructor protected : int hrs ; int mins ; int secs ; } ; // SPECIFICATION FILE ( time.h)
  • 21. 21 Class Interface Diagram Protected data: hrs mins secs Set Increment Write Time Time Time class
  • 22. 22 Derived Class ExtTime // SPECIFICATION FILE ( exttime.h) #include “time.h” enum ZoneType {EST, CST, MST, PST, EDT, CDT, MDT, PDT } ; class ExtTime : public Time // Time is the base class and use public inheritance { public : void Set ( int h, int m, int s, ZoneType timeZone ) ; void Write ( ) const; //overridden ExtTime (int initH, int initM, int initS, ZoneType initZone ) ; ExtTime (); // default constructor private : ZoneType zone ; // added data member } ;
  • 23. 23 Class Interface Diagram Protected data: hrs mins secs ExtTime class Set Increment Write Time Time Set Increment Write ExtTime ExtTime Private data: zone
  • 24. 24 Implementation of ExtTime Default Constructor ExtTime :: ExtTime ( ) { zone = EST ; } The default constructor of base class, Time(), is automatically called, when an ExtTime object is created. ExtTime et1; hrs = 0 mins = 0 secs = 0 zone = EST et1
  • 25. 25 Implementation of ExtTime Another Constructor ExtTime :: ExtTime (int initH, int initM, int initS, ZoneType initZone) : Time (initH, initM, initS) // constructor initializer { zone = initZone ; } ExtTime *et2 = new ExtTime(8,30,0,EST); hrs = 8 mins = 30 secs = 0 zone = EST et2 5000 ??? 6000 5000
  • 26. 26 Implementation of ExtTime void ExtTime :: Set (int h, int m, int s, ZoneType timeZone) { Time :: Set (hours, minutes, seconds); // same name function call zone = timeZone ; } void ExtTime :: Write ( ) const // function overriding { string zoneString[8] = {“EST”, “CST”, MST”, “PST”, “EDT”, “CDT”, “MDT”, “PDT”} ; Time :: Write ( ) ; cout <<‘ ‘<<zoneString[zone]<<endl; }
  • 27. 27 Working with ExtTime #include “exttime.h” … … int main() { ExtTime thisTime ( 8, 35, 0, PST ) ; ExtTime thatTime ; // default constructor called thatTime.Write( ) ; // outputs 00:00:00 EST thatTime.Set (16, 49, 23, CDT) ; thatTime.Write( ) ; // outputs 16:49:23 CDT thisTime.Increment ( ) ; thisTime.Increment ( ) ; thisTime.Write ( ) ; // outputs 08:35:02 PST }
  • 28. 28 Take Home Message • Inheritance is a mechanism for defining new class types to be a specialization or an augmentation of existing types. • In principle, every member of a base class is inherited by a derived class with different access permissions, except for the constructors