Beruflich Dokumente
Kultur Dokumente
0/
INHERITANCE
By the help of inheritance we can create more special classes from general classes.
Inheritance is one of the ways in object-oriented programming that makes
reusability possible.
Reusability
Once a class has been created and tested it can be used in different ways again.
1. The simplest way to reuse a class is to just use an object of that class
directly. The standard library of the C++ has many useful classes and objects.
For example, cin and cout are such built in objects. Another useful class is string ,
which is used very often in C++ programs.
2. The second way to reuse a class is to place an object (or a pointer) of that
class inside a new class. We call this creating a member object. (Has a relation)
Your new class can be made up of any number and type of other objects, in any
combination that you need to achieve the functionality desired in your new class.
Because you are composing a new class from existing classes, this concept is
called composition (or more generally, aggregation). Composition is often
referred to as a has-a relationship. See the example e410.cpp
Function libraries were a step in the right direction, but, functions dont model
the real world very well, because they dont include important data.
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.1
6.2
// Empty strings
// Initialized
// Also initialized
// Assigning to a string
// Combining strings
// Appending to a string
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
Finally, note that cout already knows what to do with strings, so you can just
send a string (or an expression that produces a string, which happens with
s1 + s2 + "!" directly to cout in order to print it.
See Example: e61.cpp
6.3
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.4
Inheritance
OOP provides a way to modify a class without changing its code.
This is achieved by using inheritance to derive a new class from the old one.
The old class (called the base class) is not modified, but the new class (the
derived class) can use all the features of the old one and additional features of its
own.
A "Kind of" or "is a " Relationship
We know that PCs, Macintoshes and Cray are kinds of computers;
a worker, a section manager and general manager are kinds of employee.
If there is a "kind of" relation between two objects then we can derive one from
other using the inheritance.
Generalization - Specialization
By the help of inheritance we can create more special classes from general classes.
Employee worker manager (Manager is a worker, worker is an employee.)
Vehicle air vehicle helicopter (Vehicle is general, helicopter is special)
Special classes may have more members (data and methods) than general classes.
Inheritance Syntax
The simplest example of inheritance requires two classes: a base class and a
derived class.
The base class does not need any special syntax. The derived class, on the other
hand, must indicate that its derived from the base class.
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.5
6.6
License: http://creativecommons.org/licenses/by-nc-nd/3.0/
int main()
{
Teacher teacher1;
Principal principal1;
principal1.setName("Principal 1");
teacher1.setName("Teacher 1");
principal1.setSchool("Elementary School");
return 0;
}
Objects in Memory:
Object of Teacher
Object of Principal
name
age
numOfStudents
name
age
numOfStudents
school_name
numOfTeachers
setName
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
An object of a derived class inherits all the member data and functions of the
base class.
Teacher
string name
int age,numOfStudents
Thus the child (derived) object principal1 contains not only data items
school_name, numOfTeachers, but data items name; age,numOfStudents as well.
PLUS
string school_name
int numOfTeachers
void setSchool(const string &)
The principal1 object can also access, in addition to its own member function
setSchool(),
the member function that is inherited from Parent (Base), which is setName().
Private members of the base class are inherited by the derived class, but they are
not visible in the derived class.
The members of the derived class can not access private members of the base
class directly.
Principal
The derived class may access them only through the public interface of the base
class.
setSchool
1999-2010 Dr. Feza BUZLUCA
6.7
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
class Teacher{
// Base class
protected:
string name;
int age, numOfStudents;
public:
void setName (const string & new_name) { name = new_name; }
void print() const;
};
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.10
Examples:
6.8
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.11
Access Control
Remember, when inheritance is not involved, class member functions have
access to anything in the class, whether public or private,
but objects of that class have access only to public members.
Once inheritance enters the picture, other access possibilities arise for
derived classes.
Member functions of a derived class can access public and protected
members of the base class, but not private members.
Objects of a derived class can access only public members of the base class.
Access Specifier
public
Accessible from
Own Class
yes
Accessible from
Derived Class
yes
Accessible from
Objects (Outside Class)
yes
protected
yes
yes
no
private
yes
no
no
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.12
License: http://creativecommons.org/licenses/by-nc-nd/3.0/
Example:
class Teacher{
// Base class
private:
// only members of Teacher can access
string name;
protected:
// Also members of derived classes can
int age, numOfStudents;
public:
// Everyone can access
void setName (const string & new_name){ name = new_name; }
void print() const;
};
int main()
{
Teacher teacher1;
Principal principal1;
teacher1.numOfStudents = 100;
teacher1.setName("Ali Bilir");
principal1.setSchool("stanbul Lisesi");
// ERROR! (protected)
// OK (public)
// OK (public)
return 0;
}
Protected vs. Private Members
6.13
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.15
6.14
Public Inheritance
In inheritance, you usually want to make the access specifier public.
class Base
{ };
class Derived : public Base {
This is called public inheritance (or sometimes public derivation).
The access rights of the members of the base class are not changed.
Objects of the derived class can access public members of the base class.
Public members of the base class are also public members of the derived class.
Private Inheritance
class Base
{ };
class Derived : private Base {
This is called private inheritance.
Now public members of the base class are private members of the derived class.
Objects of the derived class can not access members of the base class.
Member functions of the derived class can still access public and protected
members of the base class.
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.16
Access specifications of public members of the base class can be redefined in the
derived class.
When you inherit privately, all the public members of the base class become
private.
If you want any of them to be visible, just say their names (no arguments or
return values) along with the using keyword in the public section of the derived
class:
int main(){
private
protected
public
Class C: private A
Class B: public A
ObjA
private
protected
protected
Not allowed
ObjC
1999-2010 Dr. Feza BUZLUCA
class Base{
private:
int k;
public:
int i;
void f();
};
Base b;
Derived d;
b.i=5;
d.i=0;
b.f();
d.f();
return 0;
// OK public in Base
// ERROR private inheritance
// OK
// OK
};
class Derived : private Base{ // All members of Base are private now
int m;
public:
using Base::f;
// f() is public again , i is still private
void fb1();
};
public
public
ObjB
Anyone can derive one class from another and thus gain access to the base
classs protected data. Its safer and more reliable if derived classes cant
access base class data directly.
Class A
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
private
6.17
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.18
License: http://creativecommons.org/licenses/by-nc-nd/3.0/
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.19
6.20
If the base class has a constructor, which must take some arguments, then the
derived class must also have a constructor that calls the constructor of the base
with proper arguments.
See Example: e65.cpp
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.21
B::display();
cout << intC << ", " << floC;
}
~C() { cout << "Destructor C" << endl; }
};
int main()
{
C c(1, 1.1, 2, 2.2, 3, 3.3);
cout << endl << "Data in c = ";
c.display();
return 0;
}
See Example: e67.cpp
Result:
Start
B constructor
C constructor
End
C destructor
B destructor
6.24
License: http://creativecommons.org/licenses/by-nc-nd/3.0/
t e x t \0
// assignment operator
// Other methods
6.25
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
t e x t \0
t e x t 2 \0
6.26
In this method the assignment operator of the String is called with an argument
of type (String2 &). Actually, the operator of String class expects a parameter of
type (String &).
This does not cause a compiler error, because as we will see in Section 7, a
reference to base class can carry the address of an object of derived class.
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
Inheritance: is a relation
vs.
Every time you place instance data in a class, you are creating a has a
relationship.
6.27
If there is a class Teacher and one of the data items in this class is the teachers
name, I can say that a Teacher object has a name.
This sort of relationship is called composition because the Teacher object is
composed of these other variables.
Remember the class ComplexFrac. This class is composed of two Fraction objects.
Composition in OOP models the real-world situation in which objects are composed
of other objects.
Inheritance in OOP mirrors the concept that we call generalization - specialization
in the real world.
If I model workers, managers and researchers in a factory, I can say that these
are all specific types of a more general concept called an employee.
Every kind of employee has certain features: name, age, ID num, and so on.
But a manager, in addition to these general features, has a department that he/she
manages.
In this example the manager has not an employee. The manager is an employee
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.28
You can use composition & inheritance together. The following example shows the
creation of a more complex class using both of them.
class C : public B { // Inheritance, C is B
class B {
class A {
A a;
// Composition, C has A
int i;
int i;
public:
A(int ii) : i(ii)
{}
~A() {}
void f() const
{}
};
public:
B(int ii) : i(ii) {}
~B() {}
void f() const {}
};
public:
C(int ii) : B(ii), a(ii) {}
~C() {}
// Calls ~A() and ~B()
void f() const {
// Redefinition
a.f();
B::f();
}
};
C inherits from B and has a member object (is composed of) of type A. You can
see the constructor initializer list contains calls to both the base-class
constructor and the member-object constructor.
The function C::f( ) redefines B::f( ), which it inherits, and also calls the baseclass version. In addition, it calls a.f( ).
Notice that the only time you can talk about redefinition (overriding) of functions
is during inheritance; with a member object you can only manipulate the public
interface of the object, not redefine it.
In addition, calling f( ) for an object of class C would not call a.f( ) if C::f( ) had
not been defined, whereas it would call B::f( ).
See Example: e69.cpp
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.29
Multiple Inheritance
Multiple inheritance occurs when a class inherits from two or more base classes,
like this:
int main()
{
class Base1{
public:
void f1()
char *f2(int);
};
Derived d;
float y=d.f1(3.14);
d.f3();
d.f4();
d.Base2::f4();
return 0;
// Base 1
class Base2{
// Base 2
public:
char *f2(int, char);
int f3();
void f4();
};
Base1
+
Base2
// ERROR !
d.f1();
Derived
// Derived::f1
// Base2::f3
// Derived::f4
// Base2::f4
// Base1::f2
or
char *cc = d.Base2::f2(1,'A'); // Base2::f2
See Example: e610.cpp
1999-2010 Dr. Feza BUZLUCA
6.30
License: http://creativecommons.org/licenses/by-nc-nd/3.0/
Gparent
Mother
class Gparent
{
protected:
int gdata;
};
and you try to access this item from Child:
Father
Child
Both Mother and Father inherit from Gparent, and Child inherits from both Mother and
Father.
Recall that each object created through inheritance contains a subobject of the
base class.
A Mother object and a Father object will contain subobjects of Gparent, and a Child
object will contain subobjects of Mother and Father, so a Child object will also contain
two Gparent subobjects, one inherited via Mother and one inherited via Father.
This is a strange situation. There are two subobjects when really there should be
only one.
http://www.faculty.itu.edu.tr/buzluca
http://www.buzluca.info
6.31
// ERROR: ambiguous
6.32
6.33