Professional Documents
Culture Documents
UNIT 2
Inheritance and Pointers
Prof. S. B. Karale
Syllabus- Unit II
between base Class and derived Class, Constructor and destructor in Derived
Class, Overriding Member Functions, Class Hierarchies, Public and Private
Inheritance, Types of Inheritance, Ambiguity in Multiple Inheritance, Virtual Base
Class, Abstract class, Friend Class , Nested Class.
Pointers: declaring and initializing pointers, indirection Operators, Memory
5
Inheritance
Inheritance is the process by which objects of one class acquire the
Bird
}
EXAMPLE
class ABC : private XYZ // private derivation
{
// members of ABC
};
Private derivation
• Public members of base → private of derived
● So public members of base(now private of derived) can be accessed
by member functions of derived
● Private members are not inheritable
Public derivation
• public members of base → public of derived
● Private members are not inheritable
9
Types of inheritance
1. single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance
Forms of inheritance
A
A A B B
B C C
A A
B C
B C D
D
Base
Class
A
Derived
Class
B
class B
{
int a; Single Inheritance : public
public:
int b;
void get_ab();
void show_a();
}; class D
{
class D : public B private:
{ int c;
int c; public:
public: int b;
void display() void get_ab();
}; void show_a();
Void display();
}
class B void B :: show_a()
{ {
int a;
public: cout << a;
int b;
}
void get_ab();
void D :: display()
void show_a();
{
};
cout << “a :=” << show_a();
cout << “b := ” << b;
class D : public B
cout << “c :=” << c;
{
}
int c;
public:
int main()
void display()
{
};
D d;
d.get_ab();
void B :: get_ab() d.show_a();
{ d.display();
a = 5; b = 10; d.b=20;
}; d.display();
return 0;
}
Single Inheritance : private
class B
{
int a;
public:
int b;
void get_ab(); class D
void show_a(); {
private:
};
int c;
class D : private B int b;
{ void get_ab();
int c; void show_a();
public: Public:
Void display();
void display()
}
};
void B :: get_ab()
{
a = 5; b = 10;
class B };
{ void B :: show_a()
{
int a;
cout << a;
public: }
int b; void D :: display()
void get_ab(); {
cout << “a :=” << show_a();
void show_a();
cout << “b := ” << b;
}; cout << “c :=” << c;
class D : private B }
{ int main()
{
int c;
D d;
public: d.get_ab(); // won’t work
void display() d.show_a(); // won’t work
d.display();
};
d.b=20; // won’t work
d.display();
return 0;
}
EFFECT OF INHERITANCE ON VISIBILITY OF MEMBERS
Not inheritable private Class B
Not inheritable
protected
public
Class D1 : public B
Not inheritableprivate Class D2 : private B private
Not inheritable
protected protected
public public
protected
18
public
Access rights of Derived Class
Type of Inheritance
Private Protected public
Private - - -
Access Control Protected Private Protected Protected
for Members
Public Private Protected public
2. Multilevel Inheritance
deriving a class from another derived class
C
Multilevel Inheritance
class student
{
protected:
int roll_num;
public:
class test
void get_num(int);
{
void put_num();
protected:
};
int roll_num;
float sub1,sub2;
class test : public student
public:
{
void get_num(int);
protected:
void put_num();
float sub1, sub2;
void get_marks(float,float);
public:
void put_marks();
void get_marks(float,float);
}
void put_marks();
};
Multilevel Inheritance
class student class result : public test
{ {
protected: float total;
int roll_num; public :
public: void display();
void get_num(int); }
void put_num();
}; int main()
{
class test : public student result res;
{ res.get_num(111);
protected: res.get_marks(75.0, 69);
float sub1, sub2; res.display();
public: return 0;
void get_marks(float,float); }
void put_marks();
};
Multilevel Inheritance
Class result
{
private:
float total;
protected:
int roll_num;
float sub1,sub2;
public:
void get_num(int);
void put_num();
void get_marks(float,float);
void put_marks();
void display();
}
3. Multiple Inheritance
deriving a class from several other base classes
A B
C
Multiple Inheritance
class M
{
protected:
int m;
public:
class P
void get_m(int);
{
};
protected:
class N
int m;
{
int n;
protected:
public:
int n;
void get_m(int);
public:
void get_n(int);
void get_n(int);
void display();
};
}
class P : public M, public N
{
public:
void display();
}
Multiple Inheritance
void M :: get_m(int x)
class M
{
{
m = x;
protected:
}
int m;
void N :: get_n(int y)
public:
{
void get_m(int);
n = y;
};
}
class N
void P :: display()
{
{
protected:
cout << m <<“ and”<< n;
int n;
}
public:
int main()
void get_n(int);
{
};
P p;
class P : public M, public N
p.get_m(10);
{
p.get_n(20);
public:
p.display();
void display();
return 0;
}
}
Ambiguity resolution in inheritance
Same function name appears in more than base class.
B C D
Hierarchical Inheritance (Example)
#include<iostream.h> class C :public A //Derived Class 2
class A //Base Class {
{ public:
public: void cube()
int a,b;
{
void getnumber()
getnumber();
{
cout<<"\n\tCube of the number ::\
cout<<"\n\nEnter Number :::\t";
t"<<(a*a*a);
cin>>a;
} }
}; };
B C
D
class A {
public:
void Fun(){
}
};
A
class B : public A {
………
};
B C
class C : public A {
……….
};
D
class D : public B, public C {
………..
};
Virtual base class
B C
inheritance.
Rules for virtual function
The virtual functions must be members of some class.
A virtual function in a base class must be defined, even though it may not
be used.
We can not have a virtual constructor, but we can have virtual destructor.
While a base pointer can points to any type of derived object, the reverse
is not true.
If a virtual function is defined in the base class, it need not be necessarily
redefined in the derived class. In such a cases, calls will invoke the base
function.
Pure virtual function
Example:
class SomeClass {
public:
};
Abstract Classes & Pure Virtual Functions
• Some classes exist logically but not physically.
• Example : Shape
– Shape s; // Legal but silly..!! : “Shapeless shape”
– Shape makes sense only as a base of some classes derived from it. Serves
as a “category”
– Hence instantiation of such a class must be prevented
However, only those members of the derived object that were inherited
void fun()
Syntax: {
void function() class myclass {
{ int i;
class class_name public:
{ void put_i(int n) { i=n; }
// class definition int get_i() { return i; }
} obj; } ob;
//function body ob.put_i(10);
} cout << ob.get_i();
}
Multiple Classes
Synatax: Example:
class student
class outer_class { int st_id;
{ public:
class dob
//class definition { public:
int dd,mm,yy;
class inner_class }dt;
{ void read()
{
//class definition dt.dd=25;
}; dt.mm=2;
dt.yy=1988;}
}; };
Polymorphism
Polymorphism
Computer Memory
Variable
Pointer Variable
Dereferencing Operator *
70
Computer memory consists of sequence of bytes arranged one after other.
71
Variable:
72
Each variable has assigned a unique address.
Variable data will be stored on a specified address.
… … 100 … …
a
Variable a’s value, i.e., 100, is
stored at memory location 1024
int a = 100;
73
Address operator (&)
emory address: n
1020 1024 1028
… … 100 … …
a
int a = 100; //get the value,
cout << a; //prints 100
cout << &a; //get the memory address
//prints 1024
74
Memory address: 1020 1024 1032
… 88 100 … … …
a b
75
Pointer Variable:
… … 100 … 1024 …
integer
76 pointer
Declaration pointer variable:
type* pointer_name;
//or
type *pointer_name;
where type is the type of data pointed to (e.g. int, char, double, user defined
type)
77
Examples:
int *n;
ABC *r;
int **p; // pointer to pointer
78
Memory address: 1020 1024 1032
… 88 100 … 1024 …
a p
We can access to the value stored in the variable pointed to by using the
… 88 100 … 1024 …
int a = 100; a p Result is:
int *p = &a; 100
cout << a << endl; 1024
cout << &a << endl; 1024 100
cout << p << " " << *p << endl; 1032
cout << &p << endl;
80
int a = 100, b = 88, c = 8;
int *p1 = &a, *p2, *p3 = &c;
p2 = &b; // p2 points to b
p2 = p1; // p2 points to a
b = *p3; //assign c to b
*p2 = *p3; //assign c to a
cout << a << b << c
Output:
888
81
Pointer with function
*p = 2 * x; p
a 8192
} 16 (8200)
}
82 p a gets 18
#include <iostream>
using namespace std;
int main ()
{
int value1 = 5, value2 = 15;
int *p1, *p2; Let’s figure out:
p1 = &value1; // p1 = address of value1 value1==10 / value2==20
p2 = &value2; // p2 = address of value2
*p1 = 10; // value pointed to by p1=10
*p2 = *p1; // value pointed to by p2= value
// pointed to by p1
p1 = p2; // p1 = p2 (pointer value copied)
*p1 = 20; // value pointed to by p1 = 20
cout << "value1==" << value1 << "/ value2==" << value2;
return 0;
}
83
Memory Management
Memory Allocation in C++
85
Memory Allocation in C++
86
Memory Allocation in C++
The memory allocation is done for function parameters and local variables.
A local variable occupies memory that the system allocates when it sees
entered, and freed when the block is exited, as many times as necessary.
87
Memory Allocation in C++
88
new
C++ uses keyword called as new to allocate memory to type also
constructs object.
Syntax
new data-type;
90
data-type could be any built-in data type
including an array
91
Heap memory deallocation.
syntax
delete data_type
92
Example
Dynamic Memory Allocation
new
int *p, n=10;
p = new int; p
new
p = new int[100]; p
new
p = new int[n]; p
93
Freeing (or deleting) Memory
94
Memory Allocation Example
Want an array of unknown size #include <iostream>
using namespace std;
void main()
{
int n;
cout << “How many students? “;
cin >> n;
int *grades = new int[n];
for(int i=0; i < n; i++){
int mark;
cout << “Input Grade for Student” << (i+1) << “ ? :”;
cin >> mark;
grades[i] = mark;
}
...
printMean( grades, n ); // call a function with dynamic array
95 ...
}
Dynamic Memory Allocation for Arrays:
96
Dynamic Memory Allocation for Objects:
97
using namespace std;
class Box
{
public:
Box() {
cout << "Constructor called!" <<endl;
}
~Box() {
cout << "Destructor called!" <<endl;
}
void show() {
cout<<“hellow world”;
}
};
int main( )
{
Box* myBoxArray = new Box[4];
myBoxArray[0].show();
delete [] myBoxArray; // Delete array
98 return 0;
}
Dynamic memory allocation for object
Ex
mybx->show();
99
Pointers to Objects
pointer.
Pointer can point to objects as well as to simple data types and arrays.
sometimes we dont know, at the time that we write the program , how many
cin>>rollno;
using namespace std;
cout<<"enter name";
class student cin>>name;
{ }
void print()
private:
{
int rollno; cout<<"roll no is "<<rollno;
}
public:
};
student():rollno(0),name("") void main ()
{} {
}
this pointer
can say that this pointer points to the current object of the class. Let’s take
an example to understand this concept.
void displayMyValues()
#include <iostream>
{
using namespace std;
cout<<num<<endl;
class Demo
cout<<ch;
{ private:
}
int num;
};
char ch;
int main()
public:
{
void setMyValues(int num, char ch)
{ Demo obj;
this->ch=ch; obj.displayMyValues();
} return 0;
}
Pointer vsArray
Array:
105
Defining Arrays
type array_name[size];
Example
int test[85];
106
Array Elements
The maximum number of elements an array can hold depends upon the
size of an array.
107
int age[5];
This is array with name age holding 5 integer values.
109
Retrieving array value
array_name[index]
10 20 30 40 50
110
Pointers and Array
While handling arrays with pointers you need to take care few things.
First and very important point to note regarding arrays is that the array
name alone represents the base address of array so while assigning the
address of array to pointer don’t use ampersand sign(&). Do it like this:
p = arr;
Incorrect:
p = &arr;
Example: Traversing the array using Pointers
#include <iostream>
using namespace std;
int main()
{
int *p; //Pointer declaration
int arr[]={1, 2, 3, 4, 5, 6}; //Array declaration
p = arr; //Assignment
for(int i=0; i<6;i++)
{
cout<<*p<<endl;
p++; //++ moves the pointer to next int position
}
return 0;
}
Output:
123456
How to increment pointer address and pointer’s value?
When we are accessing the value of a variable through pointer,
sometimes we just need to increment or decrement the value of
variable though it or we may need to move the pointer to next int
position(just like we did above while working with arrays).
// Pointer moves to the next int position (as if it was an array)
p++;
// Pointer moves to the next int position (as if it was an array)
++p;
/* All the following three cases are same they increment the
value * of variable that the pointer p points. */
++*p;
++(*p);
++*(p);
The name of an array points only to the first element not the
whole array.
1000
1004
1008
1012
1016
115
Array Name is a pointer constant
#include <iostream>
using namespace std;
void main ()
{
int a[5];
cout << "Address of a[0]: " << &a[0] << endl
<< "Name as pointer: " << a << endl;
}
Result:
Address of a[0]: 0x0065FDE4
Name as pointer: 0x0065FDE4
116
Dereferencing An Array Name
This element is
called a[0] or
*a
#include <iostream>
a[0] 2 using namespace std;
a int main(){
a[1] 4 int a[5] = {2,4,6,8,22};
a[2] cout << *a << " “ << a[0];
6 return 0;
a[3] } //main
8
a[4] 22 Output:
2 2
117
Array Names as Pointers
To access an array, any pointer to the first element can be used instead of the
name of the array.
We could replace *p by *a
#include <iostream>
a p
using namespace std;
void main(){
a[0] 2 int a[5] = {2,4,6,8,22};
a[1] 4 int *p = a;
6 cout << a[0] << " “ << *p;
a[2] }
a[3] 8
22 Output:
a[4] 2 2
118
Multiple Array Pointers
a[0]
#include <iostream>
a[0] 22
2 using namespace std;
44
void main(){
a[1] 4 p int a[5] = {2,4,6,8,22};
a[2] 6 int *p = &a[1];
cout << a[0]<< " “<< p[-1];
a[3] 8 p[0] cout << a[1] << " “ << p[0];
a[4] }
22
119
Pointer Arithmetic
Given a pointer p, p+n refers to the element that is offset from p by n
positions.
a 2 p - 1
a + 1 4 p
a + 2 6 p + 1
a + 3 8 p + 2
a + 4 22 p + 3
120
NULL pointer
int *p;
p = 0;
121
Function Pointer
Function Pointer
unlike normal data pointers (int *, char *, etc), we can have pointers to
functions.
int main()
{
#include <iostream>
void fun(int a)
void (*fun_ptr)(int) = &fun;
/* The above line is equivalent of
{ following two
cout<<"Value of a is=“<< a;
} void (*fun_ptr)(int);
fun_ptr = &fun; */
Output: // Invoking fun() using fun_ptr
Value of a is 10
(*fun_ptr)(10);
return 0;
123
}
Some interesting facts about function pointers.
pointers.
For example, in the below program, we have removed address operator ‘&’
in assignment.
We have also changed function call by removing *, the program still works.
124
Function Pointer
unlike normal data pointers (int *, char *, etc), we can have pointers to
functions.
#include <iostream>
void fun(int a)
{
cout<<"Value of a is=“<< a;
}
int main()
{
Syntax:
data-type (className::*pointerName)(parameters);
object.*pointerName
126
#include<iostream>
using namespace std;
class ABC
{
public: The *vptr1 is banded to
void fun() { cout<<"from fun"; } object of class.
};
int main() {
ABC *a;
a=new ABC();
void (ABC::*vptr1)();
vptr1=&ABC::fun;
(a->*vptr1)();
return 0;
127
}
Pointers to Pointers
address of the second pointer, which points to the location that contains
the actual value as shown below.
A variable that is a pointer to a pointer must be declared as such. This is
int **var;
accessing that value requires that the asterisk operator be applied twice
#include <iostream> // take the value using pptr
using namespace std; cout << "Value of var :" << var <<
endl;
int main ()
cout << "Value available at *ptr :"
{
<< *ptr << endl;
int var;
cout << "Value available at
int *ptr;
**pptr :" << **pptr << endl;
int **pptr;
return 0;
var = 3000;
}
// take the address of var
public: bptr->show();
void show() }
{ Output :-
cout<<”\n n1 = “<<n1; Pointer of base class points to it
cout<<”\n n2 = “<<n2; n1 = 44
} Pointer of base class points to derive class
}; n1=66
Passing Pointers to Functions in C++
following example −
int * myFunction()
{
.
.
.
}
Second point to remember is that, it is not good idea to return the address of a
local variable to outside of the function, so you would have to define the local
variable as static variable.
#include <iostream>
#include <ctime>
using namespace std;
// function to generate and retrun random numbers.
int * getRandom()
{
static int r[10];
// set the seed
srand( (unsigned)time( NULL ) );
for (int i = 0; i < 10; ++i)
{
r[i] = rand();
cout << r[i] << endl;
}
return r;
}
// main function to call above defined function.
int main ()
{
// a pointer to an int.
int *p;
p = getRandom();
for ( int i = 0; i < 10; i++ )
{
cout << "*(p + " << i << ") : ";
cout << *(p + i) << endl;
}
return 0;
}
NULL pointer
NULL is a special value that indicates an empty pointer
It is always a good practice to assign the pointer NULL to a pointer variable in case
The NULL pointer is a constant with a value of zero defined in several standard
int *p;
p = 0;
A void pointer is a pointer that has no associated data type with it.
A void pointer can hold address of any type and can be typcasted to any
type.
int a = 10;
char b = 'x';