Lecture 7
Lecture 7
1
Introduction to Inheritance
Child
2
Introduction to Inheritance
A A B C A
B C
B
A A
(d) Multi-Level Inheritance (f) Hybrid Inheritance
Defining Derived Class
• class derived-class-name : visibility-mode base-class-name
• {………};
class Base
{ .... ... .... };
int main()
{… };
Single Inheritance
// Derived class
#include <iostream>
class Rectangle: public Shape
using namespace std;
{
// Base class
public:
class Shape
int getArea()
{
{
public: return (width * height);
void setWidth(int w) }
{ };
width = w; int main(void)
} {
void setHeight(int h) Rectangle Rect;
{ Rect.setWidth(5);
height = h; Rect.setHeight(7);
} // Print the area of the object.
protected: cout << "Total area: " <<
int width; Rect.getArea() << endl;
int height; return 0;
}
};
Inheritance: Private, Protected and Public
class base_classname
{…………….};
return 0;
}
Multi Level Inheritance
when a derived class is created from another derived class,
then that inheritance is called as multi level inheritance.
class A
{ .... ... .... };
class B : public A
{ .... ... .... };
class C : public B
{ .... ... .... };
Multi Level Inheritance Example
#include <iostream> class B : public A
using namespace std; { };