DownloadClassSessionFile 9
DownloadClassSessionFile 9
DownloadClassSessionFile 9
1
Inheritance
2
Base Class, Derived Class
● Base Class
● Defines all qualities common to any derived
classes.
● Derived Class
● Inherits those general properties and adds
new properties that are specific to that class.
3
Example: Base Class
class base {
int x;
public:
void setx(int n) { x = n; }
void showx() { cout << x << ‘\n’ }
};
4
Example: Derived Class
/ Inherit as public
class derived : public base {
int y;/
public:
void sety(int n) { y = n; }
void showy() { cout << y << ‘\n’;}
};
5
Access Specifier: public
6
Example: main()
int main() {
derived ob;
ob.setx(10);
ob.sety(20);
ob.showx();
ob.showy();
}
7
An incorrect example
8
Access Specifier: private
9
Example: Derived Class
// Inherit as private
class derived : private base {
int y;
public:
void sety(int n) { y = n; }
void showy() { cout << y << ‘\n’;}
};
10
Example: main()
int main() {
derived ob;
ob.setx(10); // Error! setx() is private.
ob.sety(20); // OK!
ob.showx(); // Error! showx() is private.
ob.showy(); // OK!
}
11
Example: Derived Class
15
3 Types of Access Specifiers
16
3 Types of Access Specifiers
17
Constructor and Destructor
19
Example: Constructor of
base
class base {
int i;
public:
base(int n) {
cout << “constructing base \n”;
i = n; }
~base() { cout << “destructing base \
n”; }
};
20
Example: Constructor of derived
21
Example: main()
int main() {
derived o(10,20);
return 0;
}
constructing base
constructing derived
destructing derived
destructing base
22
Multiple Inheritance
● Type 1:
base 1
derived 1
derived 2
23
Multiple Inheritance
• Type 2:
base 1 base 2
derived
24
Example: Type 2
25
Example: Type 2
26
Example: Type 2
// Directly inherit two base classes.
class D : public B1, public B2 {
int c;
public:
D(int x, int y, int z) : B1(z), B2(y) {
c = x; }
void show() {
cout << geta() << getb() << c;}
};
27
Potential Problem
Base Base
Derived 1 Derived 2
Derived 3
28
Virtual Base Class
class base {
public:
int i;
};
29
Virtual Base Class
// Inherit base as virtual
class D1 : virtual public base {
public:
int j;
};
class D2 : virtual public base {
public:
int k;
};
30
Virtual Base Class
32
Example
34
Example
class base {
public:
int i;
base (int x) { i = x; }
virtual void func() {cout << i; }
};
35
Example
int main() {
base ob(10), *p;
derived d_ob(10);
p = &ob;
p->func(); // use base’s
func()
p = &d_ob;
p->func(); // use derived’s func()
} 37
Pure Virtual Functions
● General form:
virtual type func-name(paremeter-list) = 0
38
Example: area
class area {
public:
double dim1, dim2;
area(double x, double y)
{dim1 = x; dim2 = y;}
// pure virtual function
virtual double getarea() = 0;
};
39
Example: rectangle
40
Example: triangle
41