session 3 inheritance and derived...
TRANSCRIPT
© Tata Consultancy Services ltd. 17 August 2006 1
Session 3Session 3
Inheritance And Derived ClassesInheritance And Derived Classes
2
Prerequisites
� Awareness of programming concepts.
� Completion of C programming course
� Completion of Introduction to C++ session
� Completion of Classes and Objects session
3
Session Outline
� What is a derived class ?
� Single / Multiple Inheritance
� Adding more members
� Friend functions
� Redefinition of base class functions
� Scope Resolution
� Access Control for derived classes
� Public and private inheritance
� Publicising a member of a private base
� Ambiguities
� Class as a member of another class
� Constructor / Destructor and Equal to operator
� Conversions – Derived class to base class
4
Derived Classes
� A derived class inherits properties of its base class / classes which includes its data members and member functions.
� The inherited base class function can be redefined in the derived class.
� New members can be added to the derived class.
� Members of the base can be referred to as if they were members of derived class.
5
Class A
{
int a;
int b;
protected :
int d;
public :
f() (a =0; b =0;}
};
Class B : public A
{
int c;
public :
void g() (c=0;}
void f(); // re-defined A :: f();`
}
Derived Classes (Cont’d)
6
Void B :: 1()
{
a =1; //Error : a is a private member of class A and
//cannot be accessed by B
b =1; //Error : b is a private member of class A and cannot be
//accessed by B
d =1; //OK : d is a protected member hence can be accessed by B
c =1; //OK
}
Void h ()
{
A aa:
B aa;
aa. f(); // Calls A :: f()
bb. f(); // Calls B :: f()
bb. G(); // Calls B :: g()
bb.b =2; // Error : b is a private member of A
bb. d =3; // Error : d is a protected member of A
bb. A ::f(); //OK : Calls ‘f’ of A
Derived Classes (Cont’d)
7
� Private Members of the base class are not accessible to the derived class.
� Protected members of the base class can be used in the member functions of the derived class.
� Public members of the base class are accessible to the member of the derived class but may or may not be a accessible to the external users.
Derived Classes (Cont’d)
8
Friendship is not inherited by the derived classes
Class A
{
friend class B; A
int a;
};
Class B
{ B
};
Class C : public B
{ C
void f (A *p)
{
p->a++;//error : is not a friend of A
};
Friend Functions and Inheritance
9
Redefinition of Base Class Functions
Class A
{
int i;
public ;
void f();
};
Class B : public A
{
int j;
public ;
void f();
];
10
Direct and indirect Bases
Class C : public B
{
int e;
public ;
void ff();
};
Class A is a direct base class of B. Similarly class B is a direct base class of C.
Class A is an indirect base of class C.
A class is an indirect base, if it is not a direct base but is one of the classes in
the base list.
Base list is the union of the direct and the indirect bases of a class.
11
Access Controlvoid h()
{ C cc;
A aa;
B bb;
cc.ff(); //OK
cc.f(); //calls ‘f’ of class B
cc.a = 2; // error ;private member of class A
cc.b = 5; // error ; private member of class B
cc. A = f();// not Error
}
class A
{
public ;
void f();
};
class C : public B
{
public ;
void f();
void g();
};
void C :: g ()
{
f(); // calls f of C
A :: f(); // calls f of A
B :: f(); // calls f of B
}
12
Multiple InheritanceA class may be derived from any number of base classes
class A {};
class B {};
class C {};
class D : public A,public B, public C
{};
A class cannot be specified as a direct base class of a derived class more than once.
class D : public A,public B public A // error
{};
Indirect inheritance more than once is allowed.
class L{};
class A ; public L
{};
class B ; public L
{};
class C : public A, public B
{};
The object of C will have two sub-objects of class L.
L L
A B
C
13
Virtual base class
The problem of multiple copies of base class in child class is solved by
making the base class virtual base class.
Grand parent
Parent1 Parent2
Child
14
Virtual base classclass A //Grand parent
{
……
………
};
class B: virtual public A //Parent 1
{
…..
};
class C: virtual public A //Parent2
{
------\
};
class D: public B, public C
{
//Only cone copy of A will be inherited
}
15
Public and private inheritance
When a class is inherited by a derived class, the private members of the
base class are not inherited.
If a class inherits from the base class using public, the public data remains
public and protected data becomes protected.
If the derived class inherits the base class using protected, all the public
data and protected data of base class become protected in child
class.
If a class inherits from the base class using private, all the public data and
protected data become private.
16
Public and Private Inheritance
Public Inheritance
(accessible to subclasses and external users)
Class A
{
int a ;
int b;
protected ;
int c;
public ;
int f();
void g();
int h;
};
17
Public and Private Inheritance (Cont’d)Public Inheritance
class B : public A // publicly inherit from A
{
public :
ff() {c= 1; f(); h = 0;}
};
void g()
{
A aa ;
B bb;
bb.f();
bb.h = 1;
bb.c = 2; // error, c is protected
bb.a = 1; // error, a is private
bb.g();
};
18
Public and Private Inheritance (Cont’d)Private Inheritance (accessible to none other than the class itself)
class B : private A // privately inherit from A
{
public ;
ff () { c = 1; f() ; g (); }
};
void h ()
{
A aa;
B bb;
bb.f(); // error
bb.g(); // error
bb.c = 1; // error
bb.ff(); //OK
}
class B still retains all rights over class A.
No external user has access to member of class A.
It is almost equivalent to private class B
19
Public and Private Inheritance (Cont’d)
Private Inheritance
(accessible to none other than the class itself)
class B
{
private ;
A aa;
public ;
ff ();
};
20
Exampleclass employee
{
char *name;
short age;
short department;
float salary;
public;
void print _ Name ();
};
/* Public inheritance for class Manager*/
class Manager : public employee
{
int level;
public ;
void print _ level ();
};
21
Example (Cont’d)
class Branch_Manager : public Manager
{
char * branch;
public :
void print();
};
void Branch_Manager :: print ()
{
print_Name ();
print_level ();
printf (“%s”,branch);
}
22
Example (Cont’d)
/*Private inheritance for Manager in the same example*/
Class Manager : employee
{
int level;
public :
void print ();
};
void Branch Manger :: Print()
{
print Name(); // error private inheritance
print_level ();
printf (“%s”,branch);
}
23
When a class base is used as a private baseclass, all of its members are considered private members of the derived class. The syntax base-classname :: member-name can be used to restore access of a member to what it was in the base.
e.g.,
Class base {
public:
int publ;
protected:
int prot;
private:
int priv;
}
Class derived : private base
{
protected:
base :: prot; // protected in derived
public:
base :: publ; // public in derived
};
Example (Cont’d)
24
This mechanism cannot be used to grant access that was not already granted by the base class:
e.g.,
class derived 2 : public base
{
public:
base :: priv; // error : base :: priv is private
}
This mechanism can only be used to restore access to what it was in the base class.
Class derived3 : public base
{
protected:
base :: publ; // error :: publ was public
};
This mechanism cannot be used to remove access already granted.
Class derived4 : public base
{
private:
base :: publ; // error : base :: publ is public
};
Example (Cont’d)
25
Public and private inheritance
Good practices:
Public inheritance signifies “is a “ relation ship and it is an instance of
interface inheritance.
Private inheritance on the other hand is an implementation inheritance.
26
Access spec in derived class
A derived class can choose to change the access specification of inherited functions if it re-defines them.
class Animal
{
public:
int a;
void whoRU(){cout<<“Animal”<<endl;}
};
class Cat: public Animal
{
private:
int a;
void whoRU(){cout<<“Me, Cat”<<endl;}
};
27
Access spec in derived class
main()
{
Cat ca;
ca.a=10; //Not allowed. Private data.
ca.whoRU(); //Not allowed. Private.
ca.Animal::a=5; //Allowed.
ca.Animal::whoRU(); //Allowed.
}
28
AmbiguityAccess to base class must be unambiguous
Class A
{
Public :
int a;
int f();
int f(int);
int g();
};
Class B
{
int a;
int b();
Public :
int f();
int g;
int h();
int h(int);
};
Class C : public A, public B
{};
29
Ambiguity (Cont’d)
Void g (C *pc)
{
pc->a=1;// Error ambiguity is checked before access
// right is checked
pc->f(); // Error
pc->f(1);
pc->h(); // OK
}
30
Static Members are not inherited
Class A
{
public:
static a;
}
Class B : public A{};
Class C : public A{};
Class D : public B,public A{};
D pd;
pd.a = 1;// OK a is a static Hence, no ambiguity
Static members are not inherited.
31
Class Objects as members of another Class
e.g.,
Class A
{
public :
A (int size); // Constructor
};
Class B
{
A a1, a2;
public :
B (int size); // Constructor
~B (); // Destructor
};
32
Access rules for member function of class A
are unaffected
e.g.,
class Table
{
public :
Table ( int SizeOFTable);
};
class sophisticated
{
Table member1, member2;
public :
sophisticated (int size);
~sophisticated () ;
};
33
If a class has other class objects as members, and if classes of those objects have constructors defined in them.
then, Those constructor must be called by the constructors of the current class.
If the member classes have any default constructors then, there is no need to call them. They will be called automatically.
Sophisticated :: sophisticated (int size)
: member1 (size) member2 (size)
{}
Even if there are no data members in class sophisticated, size has to be passed as a parameter to the constructor, so as to initialize the member class constructors.
Access rules for member function of class A
are unaffected
34
Constructor rule for inheritanceConstructor of Base cannot be inherited.
For a class derived from another class that has constructors in it :
The constructors of the derived class must pass parameters to anyone, of the base class constructors, if no default constructor is defined.
Class A
{
int a;
int b;
public :
A (int,int) ;
~A ();
};
Class B : public A\
{
int C;
public :
B ();
B (int);
~B();
};
35
B :: B{} // Error
{
}
B :: B() : A (0,0)
{
c=0;
}
B :: B (int val) : A (val,0)
{
c=0;
}
Constructor rule for inheritance (Cont’d)
36
Base Class with default constructorsThere is no need to pass parameters explicitly if a base class has a default constructor. It will be called automatically.
class A
{
int a;
int b;
public :
A ();
};
class B : Public A
{
int c;
public :
B () ;
B (int) ;
};
37
Base Class with default constructors (Cont’d)
B :: B() // calls the default constructor of class A automatically
{
c =0;
}
B ::B (int i) // calls the default constructor of class A automatically.
{
c =i;
}
38
Base class with multiple constructorsClass A
{
protected :
A (char *) ;
public :
A (int);
A (int, int);
};
Class B : public A
{
public :
B (int);
B(char *);
B();
};
39
Base class with multiple constructors
(Cont’d)
B :: B (int val) : A (val) // calls A :: A (int)
{}
B :: B (char *s) : A (s) // calls A :: A (char *)
{}
The Derived class constructor should pass parameters to atleast one of the base class constructors.
The Derived class constructor can call a protected base class constructor
40
Multiple InheritanceClass A
{
public :
A (int);
};
Class B
{
public :
B (char *);
};
Class C : public A, public B
{
Public :
C(int,char *);
};
C :: C (int c, char *s) : A ( c ),B(s)
{}
41
Base and Member Initialization
The constructor of the base is always called before the derived class
constructor
Class A
{
public :
A (int) ;
A();
};
Class B
{
public :
B (int);
B();
};
42
Base and Member Initialization (Cont’d)Class C : public A, public B
{
const int a;
int &b;
public :
C (int&);
};
C:: C (int &rr) : A (1), B(2), a(3),b(rr)
// order of call is A,B,a,b
C :: C (int &rr) : b(rr), B(2), a(3), A(1)
// order call is B,A,b,a
// Base classes are always initialized first
C :: C (int &rr) : b (rr), a(3)
// order of call A,B,b,a the base class order in the declaration is used
//default constructors are called.
C :: C (int &rr) : b( r ), a(3), B(1)
//order of call B,A,a,b
//default constructor for A is called.
43
Destructor rule for Inheritance
Destructors of the base classes cannot be inherited.
Destructors for derived classes
- Should only do clean up required for itself
- Should not worry about clean up related to inherited properties
Destructor of base class is automatically called after the destructor derived
class.
e.g.,
class A
{
protected :
char *name;
public :
A (char *s) (name = strdup (s);}
~A () {if (name) free (name);}
};
44
Destructor rule for Inheritance (Cont’d)
class B : public A
{
char *dname;
public :
B (char *s) : A(s) { dname = new char [20]; strcpy (dname ,s;}
~ D() {if dname) delete dname;}
};
void f ()
{
B bb (“string”)
// calls constructor of A and then the constructor of B
// calls destructor of B then the destructor of A
}
45
class employee{
char *name;short dept;public :employee (char *nam,short dpt){
name = strdup (nam);dept = dpt;
}~employee () {free (name);}
};class manager : public employee{
char * area_name;public :manager (char *nam, short dpt,char *amam);~manager();
};manager :: manager (char *nam, short dpt,char *amam) : employee (nam, dpt){
area_name = strdup (amam);}Manager :: ~manager (){
free (area_name);}
Destructor rule for Inheritance (Cont’d)
46
Copy ConstructorsThe copy Constructor of a derived class calls the copy constructor of the base class first and
then the copy constructor of its own class. If the derived class does not have a user-defined
copy constructor and base class has a user-defined copy constructor, the base class user-
defined copy constructor is called first and then the default copy constructor derived class.
Class A
{
public :
A (A&); // user-defined copy constructor
A (int);
};
Class B:public
{
public :
B (int);
};
B b(3); //call B :: B(int)
B bb =b; //calls the copy construtor A :: A (A&) and then the
//default copy constructor of B ie B :: B(B&)
47
Conversions – Derived class to base classclass A
{
};
class B : public A
{}
void f (A *);
void h (B*);
void g()
{
A aa;
B bb:
f (&aa); //valid
h(&bb); //valid
f (&bb); //valid : implicit conversion from derived to base
h (&aa); //Error : no Implicit conversion from base to derived
}
48
Conversions – Derived class to base class (Cont’d)
A pointer to a base class can get implicitly converted to a pointer to the derived class (only if the inheritance is public)
However, there is no implicit conversion from derived to base class.
Such a conversion can however, be achieved through explicit casting, at the programmer’s own risk.
Void g ()
{
A aa;
B bb;
h((B*)&aa); // at programmers own risk
}
49
class A
{
char *name :
public :
A (char * s) {name = strdup (s);}
void f ();
~ A () { free (name); }
Class B : public A
{
public :
B (char *s) : A (s) {};
void f ();
void g();
`B() {}
};
Conversions – Derived class to base class (Cont’d)
50
Void gg ()
{
A *aa = new B (“string”);
aa->f(); // calls f of A
aa-> g(); // calls g () is not in the scope of A
B *bb = (B*) (new A (“string”)); // explicit cast to derived class
bb->f();
bb->g();
}
Private Inheritance : If B inherits from A privately, the pointer to B cannot be implicitly converted to class A pointer.
Conversions – Derived class to base class (Cont’d)
51
Redefinition of base class functionsClass A
{
public :
void f();
};
Class B : public A
{
public:
void f(); // Redefinition of f
};
Void ff ()
{
A *aa = new B; // implicit conversion from B to A
aa->f(); // calls f of class A
aa -> B :: f (); // errors : A is not derived from B
}
52
Inheritance and Pointers
class A{
public:
int a;
func(){cout<<"A"<<endl;}
A(){a=100;}
};
class B : public A
{
public:
func(){cout<<"B"<<endl;}
int b;
B(){b=200;}
};
53
Inheritance and Pointers
void main()
{
A * ptrA = new B;
//Base class pointer pointing to an instance of a child class.
ptrA->func();
// cout<<ptrA->b<<endl; //Why is this wrong?
A a;
B *ptrB =(B*)&a;
//Pointer of a child class pointing an instance of the base class!! Bad practice.
cout<<ptrB->b<<endl;
ptrB->func();
}.
54
Inheritance and Pointers
With a base class pointer points to an instance of the child class, a function func is invoked where func is a base class function overridden in child class, the func of base class is invoked.
Good practice
Do not over ride the base class function is the derived class unless the base class function is declared virtual.
Never make a child class pointer point to an instance of a base class.
55
Virtual functionsclass A{
public:
virtual void who(){cout<<"A"<<endl;}
};
class B: public A
{
public:
void who(){cout<<"B"<<endl;}
};
void main()
{ A* ptrA= new A;
ptrA->who();
delete ptrA;
ptrA = new B;
ptrA->who(); }
56
Virtual functions
Output: A, B
57
Virtual functions
If a base class contains a virtual functions f which is re-defined in the derived class, then a call f() for an object of derived class invokes derived::f() even if access is through the a pointer of base class.
Run time polymorphism is achieved using virtual functions.
58
Virtual functions
class A
{ public:
virtual void f(){cout<<“A”<<endl;}
};
class B
{ public:
virtual void g(){ cout<<“B”<<endl;}
};
class C : public A, public B
{
public:
void f(){cout<<“C”<<endl;}
void g() { cout<<“C”<<endl;}
};
59
Virtual functions
void main()
{
C cc;
A* ptrA=&cc;
B* ptrB= &cc;
ptrA->f();
ptrB->g();
}
60
Access control for virtual functions
The access controls of a virtual function are determined by its declaration and not affected by rules for a function that later override it!!
class A{
public:
virtual void who(){cout<<"A"<<endl;}
};
class B: public A
{
private:
void who(){cout<<"B"<<endl;}
};
61
Access control for virtual functions
void main()
{
A* ptrA= new B;
ptrA->who();
B* ptrB= new B;
ptrB->who(); //This won’t do!!
}
ptrA will be able to access who() defined in the derived class although it is placed under private.
However, ptrB will not be able to access it since it is declared private.
62
Explicit scope resolution
An inheriting class that redefines virtual function can call the function of its parent class by calling it explicitly using scope resolution operator.
class A{
public:
virtual void who(){cout<<"A"<<endl;}
};
class B: public A
{
private:
void who(){cout<<"B"<<endl; A::who();}
};
63
Abstract classes
An abstract class mechanism supports the notion of a general class of
which more concrete objects can be derived.
An abstract class can only be used as a base class and can not be
derived.
An abstract class is a class that has at least one pure virtual function.
A virtual function becomes pure virtual function if it is defined as
Virtual func_name()=0;
64
Inheritance of pure virtual funcs.
Pure virtual functions are inherited as pure virtual functions unless the derived classes redefine them.
class A{
public:
virtual void who()=0;
};
class B: public A
{
public:
void who(){cout<<"B"<<endl;}
};
65
Inheritance of pure virtual funcs.
void main()
{
A* ptrA= new B;
ptrA->who();
}
66
The magic of polymorphism
When we declare an abstract class, we create a lay out for a block of
memory.
class A
{
virtual void W()=0;
virtual void X()=0;
virtual void Y()=0;
virtual void Z()=0;
};
67
The magic of polymorphism
V table pointer &W
&X
&Z
&Y
Virtual function
table
68
The magic of polymorphism
Virtual function table, also called v- table is an array of pointers that point
to the implementation of the virtual functions. The first entry in the v
table contains address of function W as it is implemented in the
derived class. On left side is a pointer to v-table called v table
pointer. The pointer to abstract class points to v-table pointer which
points to v-table.
69
The magic of polymorphism
class B: public A
{
public:
int a;
float b;
}
The class B, inherits the v table structure of the base class.
70
The magic of polymorphism
V table pointer&w
&X
&Z
&Y
V table
W
X
Z
Y
pbint a
float b
71
The magic of polymorphism
class Shape
{
public:
virtual void whoRU()=0;
}
class Circle: public Shape
{
public:
void whoRU(){cout<<“Circle”<<endl;
}
class Square: public Shape
{
public:
void whoRU(){cout<<“Square”<<endl;
}
72
The magic of polymorphism
void main()
{
Animal *ptr = new Square;
ptr->whoRU();
delete ptr;
ptr = new Dog;
ptr->whoRU
}
73
Virtual destructors
C++ language specs clearly state that if an instance of a child class is delete using a pointer of the base class, the behavior is not defined.
By declaring the destructor as virtual in the base class, this will be fixed. Refer to the v- table structure.
74
Course Summary
� Knowledge of Derived Class and its usage
� Concepts of Inheritance
75
References
1. Skillport Courses (e-learning):
a) C++ Programming : Classes and Data abstraction