0% found this document useful (0 votes)
19 views58 pages

unit 2_

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views58 pages

unit 2_

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

Unit 2

Inheritance and Pointers


Prof.Ratnamala Paswan
• Reusability reduces the effort in developing the same features, also reduces the developing and
testing time

• C++ allows to reuse classes. This is done by writing a new class that reuses properties of
existing ones.

• This mechanism of deriving a new class from an old one is called


Inheritance.

• Formally, the capability of a class to derive properties and characteristics from


another class is called Inheritance.

•The old or existing class is BASE or PARENT class


•The new class is DERIVED or SUBCLASS class
Trivial Inheritance Example:

Adding specialized functions to the derived class


Base Class/ Vehicle
Parent Class

Derived Classes/ Car Truck


Sub Class

is-a relationship - Inheritance is an is-a relationship. We use inheritance only if an is-a relationship is
present between the two classes.

Sub Class: The class that inherits properties from another class is called Subclass or Derived Class.

Super Class: The class whose properties are inherited by subclass is called Base Class or Super class.
Inheritance Example

Here are some examples:

● A car is a vehicle.

● Orange is a fruit.

● A surgeon is a doctor.

● A dog is an animal.
Access Specifiers in Inheritance

A derived class can access all the non-private members of its base class.
Thus base-class members that should not be accessible to the member functions of derived classes should
be declared private in the base class.
We can summarize the different access types according to - who can access them in the following way −

Access public protected private

Same class yes yes yes

Derived classes yes yes no

Outside classes yes no no


Types of Inheritance
Public Inheritance vs Private Inheritance
A vs Protected Inheritance
Private members are not inherited

private protected public

B B B
class A
class C : protected A
{
{
private: int x;
// z is protected member
protected: int y;
// y is protected member
public: int z;
// x is not accessible
};
};
class D : private A
class B : public A
{
{
// z is private
// z is public
// y is private
// y is protected member
// x is not accessible
// x is not accessible
};
};
Constructors and Destructors in Inheritance

Since, we create objects of the derived class, it is the responsibility of the Derived class
constructor to call the Base class constructor (with or without parameters).

Whenever you create derived class object, first the base class default constructor is
executed and then the derived class's constructor finishes execution.

Note:

Whether derived class's default constructor is called or parameterised is called, the


base class's default constructor is always called inside them by the compiler (unless we
explicitly call any other type of base class constructor)
Case 1: Base class Default Constructor in Derived class Constructors
Case 2: Base class Parameterized Constructor in Derived class Parameterized Constructors
Destructors in inheritance are called in
the opposite order of that of
Constructors

Destructors of base & derived class are


called automatically
Overriding member functions using Inheritance

1. Suppose, a function with same name and set of arguments is defined in both the derived
class and the based class.

2. Now, if we call this function using the object of the derived class, the function of the derived
class will be executed.

3. This is known as function overriding in C++. The function in derived class overrides the
function in base class.
#include <iostream>
using namespace std; int main() {

class Base { Derived derived1;


public:
void print() {
derived1.print();
cout << "Base Function" <<
endl;
} return 0;
}; }
class Derived : public Base {
public:
void print() {
cout << "Derived Function"
<< endl;
}
};
Here, the same function print() is defined in both Base and

Derived classes.

So, when we call print() from the Derived object derived1, the

print() from Derived is executed by overriding the function in


Base.
Access Overridden Function in C++

To access the overridden function of the Base class, we use the scope resolution operator ::

Eg. derived2.Base::print();
Here, this statement

derived2.Base::print();

accesses the print() function of the Base class.


C++ Call Overridden Function From Derived Class
#include <iostream> class Derived : public Base {
using namespace std; public:
void print() {
cout << "Derived Function"
class Base { << endl;
public:
void print() { // call overridden function
cout << "Base Function" << Base::print();
endl; }
} };
};
int main() {
Derived derived1;

derived1.print();
return 0;
}
In this program, we have called the overridden function inside the

Derived class itself.

class Derived : public Base {


public:
void print() {
cout << "Derived Function" << endl;
Base::print();
}
};

Base::print(); calls the overridden function inside the Derived class.


Example of
Single Inheritance

Mathematics
a,b
accept()

Addition
add()
Class - A
int a
Example of
accept()
Multilevel Inheritance
display()

Class - B
int b
accept()
display()

Class - C
int c
accept()
display()
Example of
Hierarchical Inheritance

Person Name, Age

Student Employee

Marks Salary
Example of
Multiple Inheritance

Class- General_Info Class- Academic_Info


Name,age,address Marks,Grade
Accept1(),Display1() Accept2(),Display2()

Employee_Info
Empid,Salary
Accept3(),Display3()
Ambiguity in Multiple Inheritance

Mom:- swift Dad: swift

Which swift is
Rohit using..?

Rohit: swift
Ambiguity in Multiple Inheritance

The most obvious problem with multiple inheritance occurs during function overriding.

Suppose, two base classes have a same function which is not overridden in derived class.

If we try to call the function using the object of the derived class, compiler shows error.

It's because compiler doesn't know which function to call.

class base1 class derived : public base1, public base2


{ {
public:
void someFunction( ) };
{ .... ... .... }
}; int main()
class base2 {
{ derived obj;
void someFunction( )
{ .... ... .... } obj.someFunction() // Error!
}; }
Ambiguity in Multiple Inheritance

This problem can be solved using scope resolution function to specify which function to class either base1 or base2

int main()

derived obj;

obj.base1::someFunction( ); // Function of base1 class is called

obj.base2::someFunction(); // Function of base2 class is called

}
Virtual Base-Class

Virtual base classes are used in virtual inheritance in a way of preventing

“multiple instances” of a given class appearing in an inheritance hierarchy


when using multiple inheritances.

Need for Virtual Base Classes:

Consider the situation where we have one class A which is inherited by two

other classes B and C. Both of these classes are then inherited into another
new class D as shown in figure:
Virtual Base Class

 The data members & functions of class A are inherited twice to class D.

 One through class B and second through class C.

 When any data member or member function of class A is accessed by an


object of class D, ambiguity arises as to which data member or member
function should be called? (one inherited through B or the other inherited
through C).

 This confuses compiler and it displays error.


Virtual Base Class

Solution:

How to resolve this issue?

To resolve this ambiguity when class A is inherited in class B and class C, it is declared as
virtual base class by placing a virtual keyword the inheritances as :

Syntax for Virtual Base Classes: Syntax 1:


class B : virtual public A
{
};

Syntax 2:
class C : public virtual A
{
};
Friend Class

We know that Data hiding is a fundamental concept of object-oriented programming.

It restricts the access of private members from outside of the class and that is why, a class cannot access

the private members of other class.

Similarly, a class that doesn’t inherit another class cannot access its protected members.

Friend Class:

- A friend class is a class that can access the private and protected members of a class in which it is

declared as friend.

- This is needed when we want to allow a particular class to access the private and protected

members of a class.
Friend Class

Like friend functions, we can also use a friend class in C++ using the friend keyword.
For example,
Class B
{
//here class B can access private data members of class A
}

Class A
{

friend class B;
}

Now, since classB is a friend class, its member functions can access all members of classA
Friend Class
#include <iostream>
using namespace std; class ABC {
public:
class XYZ { void disp(XYZ obj){
cout<<obj.ch<<endl;
private: cout<<obj.num<<endl;
char ch='A'; }
int num = 11; };

public:
/* This statement would make
class ABC a friend class of XYZ, int main() {
this means that ABC can access ABC obj;
the private and protected members XYZ obj2;
of XYZ class. obj.disp(obj2);
*/ return 0;
friend class ABC; }
};
Pointers in C++

What are Pointers?


• A pointer is a variable whose value is the address of another variable, i.e., direct address of the
memory location.
• Like any variable or constant, you must declare a pointer before using it to store any variable address.
• The general form of a pointer variable declaration is −

data_type *pointer_name;

int *ip // pointer to integer variable

float *fp; // pointer to float variable

double *dp; // pointer to double variable

char *cp; // pointer to char variable


Initialization of Pointer variable
• Pointer Initialization is the process of assigning address of a variable to a pointer variable.

• Pointer variable can only contain address of a variable of the same data type.

• address operator & is used to determine the address of a variable.

• The & (immediately preceding a variable name) returns the address of the variable
associated with it.

void main()
{
int a = 10;
int *ptr; //pointer declaration
ptr = &a; //pointer initialization
}
Pointers & Arrays

In C++, pointers can no only store the address of a single variable, it can also store the address of
cells of an array.

Consider this example: int *ptr; • Here, ptr is a pointer variable while
int arr[5]; arr is an int array.

ptr = arr; • The code ptr = arr; will store


the address of the 0th element of the
array in pointer variable ptr.

int *ptr;
int arr[5];
ptr = &arr[0];

The addresses for the rest of the array elements are given by &arr[1], &arr[2], &arr[3],
and &arr[4].
Pointing to Every Array Elements

Suppose we need to point to the 3rd element of the array using the same pointer ptr.

So, if ptr points to the 0th element initially, then ptr + 3 will point to the 3rd element.

int *ptr;
For example,
int arr[5];
ptr = arr;

ptr + 1 is equivalent to &arr[1];


ptr + 2 is equivalent to &arr[2];
ptr + 3 is equivalent to &arr[3];
ptr + 4 is equivalent to &arr[4];
Pointing to Every Array Elements

Suppose, if we have initialized ptr = &arr[2]; then

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 of Pointers

An array of pointers is a collection of addresses of the same type.

Each element in this array is a address

For example,
int *ptr[5];
int arr[5]={1,2,3,4,5};

ptr[0]= &arr[0];
ptr[1]= &arr[1];
ptr[2]= &arr[2];
:
:
Home Assignment:
Write a C++ program to have an array initialized with 10 integer values and a
array pointer. Accept a number from user and traverse the array using the pointer
to check whether the number is present in the array.
Pointers to Functions

• Pointers are used to point some variables, similarly, the function pointer is a pointer used to

point functions.

• It is basically used to store the address of a function.

• We can call the function by using the function pointer.


Syntax for declaration of function pointer:
return-type (*function Pointer)(parameters if any);

Eg.

int (*funcPtr) (int, int);

Initializing the funtion pointer:

funcPtr=function_name;
Pointers to Function Example

#include <iostream> int main()

using namespace std; {

int add(int a , int b) int (*funcptr)(int, int); // function pointer declaration

{ funcptr=add; // funcptr is pointing to the add function

return a+b; int sum= funcptr(5, 5);

} cout << "value of sum is :" <<sum;

return 0;

}
Pointers to Objects

class Simple
{
public:
int a;
};

int main()
{
Simple obj;
Simple* ptr; // Pointer of class type

ptr = &obj;

cout << obj.a;


cout << ptr->a; // Accessing member with pointer
}
Pointers to Objects
1. Object pointers are usually used to create objects at run-time and bind the function with
any particular class at run-time.

Eg. Sample_Class *ptr ;


Sample_Class *ptr ;
Sample_Class obj ;
2. ptr will always hold address of any object of Sample_Class
ptr = &obj ;

3. Member functions are accessed through object pointer using arrow operator ()
ptr display()
4. We can create objects at run-time using “new” operator and refer to it using a pointer

Sample_Class *ptr = new Sample_Class ;

5. Parameters can be passed for object creation: Sample_Class *ptr = new Sample_Class (5, 10);
Pointer to Array of Objects

1. Creating array of objects using pointer Sample_Class *ptr = new Sample_Class [10] ;

• This creates 10 objects and the pointer “ptr” will point to the first object’s
memory location
• ptr++ will make the pointer point at the next object

Array of Pointers to Objects

1. Creating array of pointers to objects is used to access each object individually


Sample_Class *ptr [10] ; // This creates array of 10 pointers of type Sample_Class

ptr[i] = new Sample_Class; // separately creates each object in memory and assigns the returned
address to ptr[i]

ptr[i]  getdetails(); // Call to member functions for each of the dynamically created objects using
address of that object
“this” Pointer

● C++ provides a keyword 'this', which represents the current object and
passed as a hidden argument to all member functions.

● The this pointer is a constant pointer that holds the memory address of
the current object.

● The this pointer is not available in static member functions, as static


member functions can be called without any object (i.e. with class name).
“this” Pointer
#include <iostream>
using namespace std; int main()
{
class sample sample x;
{
int a,b; x.input(5, 8);
public: x.output();
void input(int a, int b)
{ return 0;
a=this->a; }
b=this->b;
}
void output()
{
cout<<"a = "<<a<<endl<<"b = "<<b;
}
};
“this” Pointer
When “this” is used..??
● When the any data member’s name and the name of local variable in any
function is same
● When we want to return the current object (i.e. object pointed by this pointer)
Pointers to Pointers

• A pointer to a pointer is a form of multiple indirection or a chain of pointers.


• Normally, a pointer contains the address of a variable.
• When we define a pointer to a pointer, the first pointer contains the address of the
second pointer, which points to the location that contains the actual value as shown
below:
Pointers to Pointers

A variable that is a pointer to pointer must be declared by placing an


additional asterisk in front of its name.

For example, following is the declaration for a pointer to a pointer of type int −
int **var;
Pointers to Derived Class
In C++, we can declare a pointer that points to the address of base class as well as derived class objects.

base b; base
base *bptr;
bptr=&b;

derive d;
bptr=&d; derived
Passing pointers to functions
• If a pointer is passed to a function as a parameter and tried to be modified then the changes made to
the pointer does not reflects back outside that function.

• This is because only a copy of the pointer is passed to the function. It can be said that “pass by
pointer” is passing a pointer by value.

#include <iostream> int main()


using namespace std; {
int var = 23;
int global_var = 42; int* ptr= &var;

// function to change pointer value cout << "Passing Pointer to function:" << endl;

void changePointerValue(int* p) cout << "Before :" << *ptr<< endl; // displays 23
{
p = &global_var; changePointerValue(ptr)
}
cout << "After :" << *ptr << endl; // displays 23

return 0;
}
Return Pointer from Function
• A function can return data of types int , float, char, etc.

• Similarly, a function can return a pointer to data. The syntax of a function returning a
pointer is as follows:

• Syntax: type* function_name(type1, type2, ...);


#include<iostream>
using namespace std; int *abc()
int *abc(); // this function returns a pointer of {
type int int x = 100, *p;
p = &x;
int main() return p;
{ }
int *ptr;
ptr = abc();
cout<<*ptr;
return 0;
}
Null Pointer
● It is always a good practice to assign the pointer NULL to a pointer variable in case
you do not have exact address to be assigned.
● This is done at the time of variable declaration.
● A pointer that is assigned NULL is called a null pointer.

#include <iostream>

using namespace std;


int main () {
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;

return 0;
}
● If a pointer contains the null value, it is assumed to point to nothing.
Void Pointer

• 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 type casted to any type.

int a = 10;
char b = 'x';

void *p = &a; // void pointer holds address of int 'a'

p = &b; // void pointer holds address of char 'b'

You might also like