Inheritance
Inheritance
Inheritance
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.
Example: Base Class
class base {
int x;
public:
void setx(int n) { x = n; }
void showx() { cout << x << ‘\n’ }
};
Example: Derived Class
// Inherit as public
class derived : public base {
int y;
public:
void sety(int n) { y = n; }
void showy() { cout << y << ‘\n’;}
};
Access Specifier: public
int main() {
derived ob;
ob.setx(10);
ob.sety(20);
ob.showx();
ob.showy();
}
An incorrect example
// Inherit as private
class derived : private base {
int y;
public:
void sety(int n) { y = n; }
void showy() { cout << y << ‘\n’;}
};
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!
}
Example: Derived Class
class base {
int i;
public:
base(int n) {
cout << “constructing base \n”;
i = n; }
~base() { cout << “destructing base \n”; }
};
Example: Constructor of derived
int main() {
derived o(10,20);
return 0;
}
constructing base
constructing derived
destructing derived
destructing base
Multiple Inheritance
Type 1:
base 1
derived 1
derived 2
Multiple Inheritance
• Type 2:
base 1 base 2
derived
Example: Type 2
Base Base
Derived 1 Derived 2
Derived 3
class base {
public:
int i;
};
Virtual Base Class
class base {
public:
int i;
base (int x) { i = x; }
virtual void func() {cout << i; }
};
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()
}
Pure Virtual Functions
General form:
virtual type func-name(paremeter-list) = 0
Example: area
class area {
public:
double dim1, dim2;
area(double x, double y)
{dim1 = x; dim2 = y;}
// pure virtual function
virtual double getarea() = 0;
};
Example: rectangle