Inheritance
Inheritance
Lecture
Inheritance
Inheritance
Definition:
“Process of extending existing class into new class is known as
inheritance”
• Existing class is known as Base Class (or Parent Class)
• New class is known as Derived Class (or Child Class)
Vehicle Polygon
class class
Syntax
class Child : public Parent {
class ChildClass: public BaseClass public:
{ int multiply()
... {
}; return x * y;
}
#include <iostream> };
using namespace std;
• Public
• Protected
• Private
Member access in
Base Class Derived Class
Public Public
Protected Protected
Private Hidden
Protected Inheritance
Member access in
Base Class Derived Class
Public Protected
Protected Protected
Private Hidden
Private Inheritance
Member access in
Base Class Derived Class
Public Private
Protected Private
Private Hidden
Inheritance (example)
#include <iostream>
using namespace std;
class Polygon {
private:
int width, height;
public:
void set_values(int a, int b)
{
width = a; height = b;
}
int get_width()
{
return width;
}
int get_height()
{
return height;
}
};
Inheritance (example)
#include <iostream>
using namespace std; class Rectangle : public Polygon {
public:
class Polygon { int area()
private: {
int width, height; return get_width() * get_height();
public: }
void set_values(int a, int b) };
{
width = a; height = b;
}
int get_width()
{
return width;
}
int get_height()
{
return height;
}
};
Inheritance (example)
#include <iostream>
using namespace std; class Rectangle : public Polygon {
public:
class Polygon { int area()
private: {
int width, height; return get_width() * get_height();
public: }
void set_values(int a, int b) };
{
width = a; height = b;
}
int get_width() int main()
{ {
return width; Rectangle rec1;
} rec1.set_values(4, 5);
int get_height() cout << rec1.area();
{ return 0;
return height; }
}
};
Inheritance (example)
#include <iostream>
using namespace std; class Rectangle : protected Polygon {
public:
class Polygon { int area()
private: {
int width, height; return get_width() * get_height();
public: }
void set_values(int a, int b) };
{
width = a; height = b;
}
int get_width() int main()
{ {
return width; Rectangle rec1;
} rec1.set_values(4, 5); Error
int get_height() cout << rec1.area();
{ return 0;
return height; }
}
};
Inheritance (example)
#include <iostream>
using namespace std; class Rectangle : private Polygon {
public:
class Polygon { int area()
private: {
int width, height; return get_width() * get_height();
public: }
void set_values(int a, int b) };
{
width = a; height = b;
}
int get_width() int main()
{ {
return width; Rectangle rec1;
} rec1.set_values(4, 5); Error
int get_height() cout << rec1.area();
{ return 0;
return height; }
}
};
Thanks a lot