C - Inheritance
C - Inheritance
C++ Program
6. Inheritance
House h;
h.lamps[0].on();
Examples for compositions 4
House h;
h.switch_off_lamps();
C++ Inheritance 5
Derived classes
Inherit all members of the base class (data and methods)
Can be used instead of the base class
Example
Vehicle
BMW VW
C++ Inheritance: Syntax 6
Syntax
class Child : [access-control] Parent
{…};
Example
class Parent { … };
Example: intro.cpp
C++ Inheritance: Access-control 7
Example: accesscontrol.cpp
C++ Inheritance: Invoke parent constructors 8
Example
class Parent
{
Parent(int i) { … }
};
Example
class Parent
{
Parent(int i) { … }
};
Example
class Lamp
{
Lamp(int brightness) { … }
};
class Parent
{
Parent(int i) { … }
};
Demo: initialization.cpp
C++ Inheritance: Name hiding 12
Example
class Base
{
public: void f(int i);
};
Derived d;
d.f();
Example: namehiding.cpp
Example: namehiding2.cpp
C++ Inheritance: Multiple Inheritance 13
- d.C::x = 1; //OK
- d.B::A::x = 1; //OK
Example: multipleinheritance.cpp
C++ Inheritance: Virtual inheritance 14
Multiple Inheritance
Detailed Knowledge required to access parent members
Often there is no need for a duplicate set of members
Virtual inheritance
Only one set of members available, no matter how often a base
class is sub-classed
No ambiguities when using members from the base class
(Solvable) problems when passing parameters to base constructors
D
A, B, C
Example: virtualinheritance.cpp
15
C++ Inheritance: Interchange base and derived Classes
Example: pointers.cpp
C++ Inheritance: Pointers to classes 16
Derived
Memory address
Base Base
class B : public A {
void f () { ... } //Redefinition: B::f redefines A::f
};
A *a;
B *b;
a = new A;
a->f(x); //Invokes A::f
b = new B;
b->f(x); //Invokes B::f, A::f is hidden
Static Binding
Compiler decides at compile-time
which method is invoked