Unit II - Inheritance & Pointers Final
Unit II - Inheritance & Pointers Final
Unit II - Inheritance & Pointers Final
Syllabus:-
Inheritance- Base Class and derived Class, protected members, relationship 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.
The capability of a class to derive properties and characteristics from another class is
called Inheritance.
It allows software developers to derive a new class from the existing class. The derived class
inherits the features of the base class (existing class).
Inheritance
};
Access specifier can be public, protected and private.
The default access specifier is private.
Inheritance
Private Yes No No
Protected Yes Yes No
Public Yes Yes Yes
Modes of Inheritance
Public mode:
If derive a sub class from a public base class. Then the public member of the base class will
become public in the derived class and protected members of the base class will become protected in
derived class.
Protected mode:
If derive a sub class from a Protected base class. Then both public member and protected
members of the base class will become protected in derived class.
Private mode:
If derive a sub class from a Private base class. Then both public member and protected members
of the base class will become Private in derived class.
Modes of Inheritance
Inheritance
Protected Member
The class member declared as Protected are inaccessible outside the class but they can
be accessed by any subclass(derived class) of that class.
class Parent // base class int main()
{ {
protected: int num; Child obj1;
}; obj1.setId(81);
class Child : public Parent obj1.displayId();
// sub class or derived class return 0;
{ }
public:
void setId(int id) {
num = id;
}
void displayId()
{
cout << "id_protected is:" << num;
}
};
Inheritance
Relationship between base Class and derived Class
The hierarchical relationship between derived class and base class is known as an “is a” relationship.
A derived class can access all the non-private members of its base class.
The derived class can add new members or change base class members.
Types of Inheritance in C++
1. Single Inheritance
2. Multiple Inheritance
3. Hierarchical Inheritance
4. Multilevel Inheritance
5. Hybrid Inheritance (also known as Virtual
Inheritance)
Types of Inheritance in C++
Types of Inheritance in C++
Single Inheritance
In this inheritance, a single class inherits the properties of a base class. All the data
members of the base class are accessed by the derived class according to the visibility mode
(i.e., private, protected, and public) that is specified during the inheritance.
#include <iostream> // derived class
using namespace std; class Computer: public
// base class int main()
electronicDevice
class electronicDevice {
{
{ // create object of the derived
public:
public: class Computer obj;
// constructor of the derived class // constructor of base class and
// constructor of the base Computer() derived class will be called
class electronicDevice() { return 0;
{ cout << "I am a computer.\n\ }
cout << "I am an electronic device.\ n";
n\n"; }
} };
};
Types of Inheritance in C++
Multiple Inheritance
The inheritance in which a class can inherit or derive the characteristics of multiple
classes, or a derived class can have over one base class, is known as Multiple Inheritance
If the object of child class needs to access one of the same named
member function then it results in ambiguity. The compiler is confused
as method of which class to call on executing the call statement.
Ambiguity in Multiple Inheritance
class Base1 class Derived : public Base1, public Base2
{ {
public:
};
void someFunction( )
{ int main()
.... ... .... {
} Derived obj;
};
obj.someFunction() // Error!
class Base2
{ return 0;
public: }
void someFunction( )
{ This problem can be solved using scope resolution operator. e.g.
.... ... ....
} int main()
}; {
Derived obj;
obj.base1::someFunction( ); // Function of base1 class is called
Base class constructors are called first and the derived class constructors
are called next in single inheritance.
• In multiple inheritance
Constructors from all base class are invoked first and then derived class constructor is
called.
• Order of constructor invocation depends on the order of how the base is inherited.
• The constructor of base class is called first to initialize all the inherited members.
class Base1 class Base2
{ {
public: public:
Base1() Base2()
{ {
cout<<"\nBase1 constructor"; cout<<"\nBase2 constructor";
} }
~Base1() ~Base2()
{ {
cout<<"\nDestructor Base1"; cout<<"\nDestructor Base2";
} }
}; };
Constructor and destructor in Derived Class
};
Constructor and destructor in Derived Class
To call the parameterized constructor of base class when derived class’s parameterized
constructor is called, you have to explicitly specify the base class’s parameterized constructor
in derived class
#include <iostream>
using namespace std;
// base class
class Parent
{
public: // base class's parameterised constructor
Parent(int i)
{
int x =i;
cout << "Inside base class's parameterised constructor" ;
}
};
Constructor and destructor in Derived Class
// sub class
class Child : public Parent
{
public: // sub class's parameterised constructor
Child(int j): Parent(j)
{
cout << "Inside sub class's parameterised constructor" ;
}
};
// main function
int main()
{
Child obj1(10);
return 0;
}
Multilevel Inheritance
The inheritance in which a class can be derived from another derived class is known as Multilevel
Inheritance. Suppose there are three classes A, B, and C. A is the base class , B is the derived class
of A. Now, C is the class that is derived from class B This makes class B, the base class for class C
but is the derived class of class A
class base_classname
{ properties;
methods;
};
The inheritance in which a single base class inherits multiple derived classes is known as
the Hierarchical Inheritance.
This inheritance has a tree-like structure since every class acts as a base class for one or
more child classes.
Hierarchical Inheritance
Hybrid Inheritance, as the name suggests, is the combination of two or over two types of
inheritances.
For example, the classes in a program are in such an arrangement that they show both
single inheritance and multiple inheritances at the same time.
Hybrid Inheritance
};
Syllabus
int main()
class Base
{
{
Derived obj;
public:
obj.Base::getdata();
void getdata()
obj. getdata();
{
return 0;
cout<<"base..";
}
}
};
class Derived:public Base
{
public: Invoke the base class
void getdata() function using base class
{
cout<<"derived..";
name and scope resolution
} operator.
};
Second Solution
To resolve this ambiguity when class A is inherited in both class B and class C,
it is declared as virtual base class by placing a keyword virtual as :
Syntax 1:
class B : virtual public A
{
};
Syntax 2:
class C : public virtual A
{
};
Virtual Base Class - Example
It is a design concept in program development & provides a base upon which other
classes may be built
Abstract classes are used to express broad concepts from which more concrete
classes can be derived.
An abstract class in C++ has at least one pure virtual function by definition. In other
words, a function that has no definition.
The aim of the class is to provide general functionality for shape, but objects of type
shape are much too general to be useful. Shape is therefore a suitable candidate for an
abstract class:
Abstract Classes
// C++ program to calculate the area of a square and a circle Int main() {
#include <iostream> Square square;
using namespace std; // Derived class Circle circle;
// Abstract class class Square : public Shape { cout << "Enter the length of the square: ";
public: square.getDimension();
class Shape {
float calculateArea() {
protected: return dimension * dimension; cout << "Area of square: " <<
float dimension; } Square.calculateArea() << endl;
public: };
void getDimension() { // Derived class cout << "\n Enter radius of the circle: ";
cin >> dimension; class Circle : public Shape { circle.getDimension();
} public:
float calculateArea() { cout << "Area of circle: " <<
// pure virtual Function return 3.14 * dimension * circle.calculateArea() << endl;
dimension; return 0; }
virtual float calculateArea() = 0;
}
}; };
Output:
Enter the length of the square: 4
Area of square: 16
Enter radius of the circle: 5
Area of circle: 78.5
Friend Class
Like a friend function, a class can also be made a friend of another class using
keyword friend.
For example:
When a class is made a friend class, all the
class B; member functions of that class becomes
class A friend functions.
{
// class B is a friend class of class A
friend class B;
In this program, all member functions
... of class B will be friend functions of class A.
.. Thus, any member function of class B can
... access the private and protected data of class
} A. But, member functions of class A cannot
class B
{ access the data of class B.
... .. ...
}
Nested Class
A nested class is a class which is declared in another enclosing class.
A nested class is a member and as such has the same access rights as any
other member.
Example:
class Outer
{
class Inner
{
};
};
Nested Class
Syntax of Pointer :
data_type *pointername;
int *ip; // pointer to an integer
double *dp; // pointer to a double
float *fp; // pointer to a float
char *ch; // pointer to character
Pointer Declaration
The * in the declaration statement is not an operator, but indicates that the name followed is a
pointer variable.
For example,
e.g.
If a number variable is stored
in the memory address 0x123,
and it contains a value 5.
Two operators new and delete that perform the task of allocating and freeing the memory in a
better and easier way.
delete[ ] pointer_variable;
delete[] p;
Memory Management
int main ()
{ 0x2100
int *ptr1 = NULL; //declaration
ptr1 = new int; //initialization Ptr1 0x108
*ptr1 = 28; //set value at address 28
float *ptr2 = new float(299.121); // initialize the memory Ptr2
cout << "Value of pointer var1 : " << *ptr1; 0x2100
cout << "Value of pointer var2 : " << *ptr2;
int *ptr3 = new int[5]; // allocate a block of memory
if (!ptr3)
{
cout << "Allocation of memory failed\n";
}
else
{ i=0 1 2 3 4
for (int i = 0; i < 5; i++)
ptr3[i] = 10; 10 10 10 10 10
cout << "Value stored in block of memory:";
for (int i = 0; i < 5; i++)
cout << ptr3[i] << " ";
}
delete ptr1; delete ptr2; delete[] ptr3;
return 0;
}
Pointers to Objects
Just like other pointers, pointers to objects are declared by placing * in front of an
object pointer’s name.
Pointers to objects aim to make a pointer that can access the object, not the
variables.
Then now question is that if only one copy of each member function exists and is used by
multiple objects, how are the proper data members are accessed and updated?
‘this’ Pointers
The ‘this’ pointer is passed as a hidden argument to all non-static member function
calls and is available as a local variable within the body of all non-static functions
Following is the situations where ‘this’ pointer is used:
When local variable’s name is same as member’s name
class Test
{
private: int main()
int x; //Local Variable {
public: Test obj;
void setX (int x) int x = 20;
{ obj.setX(x);
// The 'this' pointer is used to retrieve the object's x obj.print();
// hidden by the local variable 'x' return 0;
this->x = x; }
} OUTPUT:-
void print() { cout << "x = " << x << endl; } x = 20
};
Pointers Vs Arrays
Array Pointer
Declaration Declaration
//In C++ //In C++
type var_name[size]; type * var_name;
Stores the value of the variable of Store the address of the another
homogeneous data type. variable of same datatype.
An array of pointers can be generated. A pointer to an array can be generated.
An array can store the number of A pointer variable can store the
elements, mentioned in the size of address of only one variable at a time.
array variable.
Used to allocate fixed sized memory. Used for dynamic memory allocation.
New Keyword is used
Accessing Array Elements Using Pointer
#include <iostream>
#include <iostream>
using namespace std;
using namespace std;
int main()
{
int main()
int arr[5] = {1, 2, 3, 4, 5};
{
int *ptr = &arr[0];
int arr[5] = {5, 2, 9, 4, 1};
cout<<"The values in the array are: ";
int *ptr = &arr[2];
for(int i = 0; i < 5; i++) {
// Equivalent to -> int *ptr; ptr=&arr[2];
cout<< *ptr <<" ";
cout<<"The value in the second index of the
ptr++;
array is: "<< *ptr;
}
return 0;
return 0;
}
}
Output:- Output:-
The value in the second index of the array is: 9 The values in the array are: 1 2 3 4 5
Array and Pointer
Point to Every Array Elements access the elements using the single pointer
int *ptr; // use dereference operator
int arr[5]; *ptr == arr[0];
ptr = arr; *(ptr + 1) is equivalent to arr[1];
*(ptr + 2) is equivalent to arr[2];
ptr + 1 is equivalent to &arr[1]; *(ptr + 3) is equivalent to arr[3];
ptr + 2 is equivalent to &arr[2]; *(ptr + 4) is equivalent to arr[4];
ptr + 3 is equivalent to &arr[3];
ptr + 4 is equivalent to &arr[4];
Initialized ptr = &arr[2];
ptr - 2 is equivalent to &arr[0];
ptr - 1 is equivalent to &arr[1];
ptr + 1 is equivalent to &arr[3];
ptr + 2 is equivalent to &arr[4];
Array and Pointer
Note: The address between ptr and ptr + 1 differs by 4 bytes. It is because ptr is a pointer to an int data.
And, the size of int is 4 bytes in a 64-bit operating system.
Similarly, if pointer ptr is pointing to char type data, then the address between ptr and ptr + 1 is 1 byte.
It is because the size of a character is 1 byte.
Function Pointers
Compiler converts source code into an executable file. This executable file gets stored in RAM
All the functions and machine code instructions are data. This data is a bunch of bytes with some address in RAM.
The function pointer contains RAM address of the first instruction of a function.
Function Pointers
Address of a function
We can get the address of a function very easily. We just need to mention the name of the
function, we do not need to call the function.
Function pointers can be:-
1.#include <iostream>
2.using namespace std; 1) Passed to functions
3.int main()
4.{ 2) Returned from functions.
5. std::cout << "Address of a main() function is : " <<&main<< std::endl;
6. return 0;
7.} 3) Stored in arrays
Declaration Syntax:-
int **var;
Pointers to Pointers
int main () {
int var;
int *ptr;
int **pptr; Output:-
return 0;
}
Pointers to Derived classes
Pointers can be declared to point base or derived classes.
Base class pointer can point to objects of base and derived class.
Pointer to derived class object cannot point to objects of base class.
class Base int main()
{ class Derived : public Base {
public: { Base *p;
void fun1() public: p = new Derived ();
{ void fun4() p->fun1 ();
cout << "fun1 of Base Class" << endl; { p->fun2 ();
} cout << "fun4 of Derived Class" p->fun3 ();
void fun2() << endl; //The following statements will
{ } throw error
cout << "fun2 of Base Class" << endl; void fun5() //p->fun4 (); //error: ‘class
} { Base’ has no member named
void fun3() cout << "fun5 of Derived Class" ‘fun4’;
{ << endl; //p->fun5 (); //error: ‘class
cout << "fun3 of Base Class" << endl; } Base’ has no member named
} }; ‘fun5’;
}; }
Passing Pointers To Functions
C++ allows you to pass a pointer to a function. To do so, simply declare the function
parameter as a pointer type.
Advantages :
Flexible: can change the value of the object.
Fast: only need to copy a pointer not the whole object.
Disadvantages:
Unsafe: can change value of the variable in calling function.
Complex: variable is pointer so needs * or -> to access.
Passing Pointers To Functions
#include <iostream> int main()
#include <string> {
using namespace std; int a, b;
void swap(int* a, int* b) cout<<"Enter values for swapping";
{ cin>>a>>b;
int temp; swap(&a,&b);
temp = *a; cout<<"Swapped values"<<endl;
cout<<"a = "<<a<<"\t"<<"b = "<<b;
*a = *b;
return 0;
*b = temp;
}
}
Output:
Enter values for swapping: 3 2
Swapped values
a=2b=3
Return Pointers from Functions
• Pointers is a variable which is used to store the memory address of another variable.
• It is not recommended to return the address of a local variable outside the function as
it goes out of scope after function returns.
• So to execute the concept of returning a pointer from function in C/C++ you must define
the local variable as a static variable.
#include<iostream>
int main()
#include<cstring> {
using namespace std; int *x;
x=show();
int* show ()
{ static int p; cout<<"\n Value=";
cout<<"Enter value"; cout<<*x;
cin>>p;
return 0;
return &p; }
}
Null pointer