0% found this document useful (0 votes)
17 views96 pages

Unit 2-1

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)
17 views96 pages

Unit 2-1

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/ 96

SMT KASHIBAI NAWALE COLLEGE OF

ENGINEERING
Department of Computer Engineering

Inheritance and Pointers


Inheritance: Base class and derived class, protected members, relationship
between base class and derived class, constructor and destructor in derived class,
overriding member function, class heirachies, 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
management: new and delete, pointers to objects, this pointer, pointers vs arrays,
accessing arrays using pointers, array of pointers, function pointers, pointers to
pointers, pointers to derived classes, passing pointers to functions, return
pointers from functions, null pointer, void pointer.
-07Hours
Inheritance
• The mechanism of deriving new class from old one
is called as Inheritance.
• The new class created is called “derived class” or
“sub class”
• The existing class is known as the “base class” or
“super class”.
• It allows the user to reuse the code whenever
possible.
• A class can inherit properties from more than one
class.
Inheritance Benefits
• When a class inherits from another class, there are
three benefits:
1. You can reuse the methods and data of the existing
class
2. You can extend the existing class by adding new
data and new methods
3. You can modify the existing class by overriding its
methods with your own implementations
Base class and Derived class

• Syntax:
class <derived_class_name> : <access-specifier> <base_class_name>
{
//body
}
Example
1. class ABC : private XYZ //private derivation
{ }

2. class ABC : public XYZ //public derivation


{ }

3. class ABC : protected XYZ //protected derivation


{ }

4. class ABC: XYZ //private by default


{ }
Visibility Modes in Inheritance
Visibility Modes in Inheritance
A derived class inherits all base class methods, except:
1. Constructor, destructor, copy constructor of base
class
2. Overloaded operator of base class
3. Friend function of base class
Constructor and destructor in
Derived class
Constructor:
• Create object of derived class
• By default, object of base class is created
• Default constructor of base class is called.
• Default constructor of derived class is invoked.

Destructor:
• An object of derived class is destroyed first
• Object of base class is destroyed
Types of Inheritance
1. Single inheritance
2. Multilevel inheritance
3. Multiple inheritance
4. Hierarchical inheritance
5. Hybrid inheritance
Single Inheritance
A class is allowed to inherit from only one class.
class A
{ public:
A( )
{ cout<<“Constructor of class A”; }
};
class B: public A
{ public:
B()
{ cout<<“Constructor of class B”; }
};
int main()
{
B b1;
}
Multilevel Inheritance
A derived class is created from another derived
class.
class A
{ public:
A( )
{ cout<<“Constructor of class A”; }
};
class B: public A
{ public:
int main()
B()
{
{ cout<<“Constructor of class B”; } C c1;
}; }
Class C: public B
{ public:
C()
{ cout<<“Constructor of class C”; }
};
Multiple Inheritance
One subclass is derived from more than one base
class.
The number of base classes will be separated by a
comma ( , ) and the access mode for every base
class must be specified.
class A
{ public:
A( )
{ cout<<“Constructor of class A”; }
};
class B
{ public:
int main()
B()
{
{ cout<<“Constructor of class B”; } C c1;
}; }
class C: public A, public B
{ public:
C()
{ cout<<“Constructor of class C”; }
};
Ambiguity in Multiple
Inheritance

Class A Class B
display() display()

Class C Main()
C c1;
c1.display();
Ambiguity in Multiple
Inheritance
To solve this ambiguity scope resolution operator :: is used.
ObjectName.ClassName::FunctionName()

Main()

C c1;
c1.A::display();
Hierarchical Inheritance
More than one subclasses are derived from a
single base class
class A
{ public:
A( ) { cout<<“Constructor A”; }
};
class B : public A
{ public:
B( ) { cout<<“Constructor B”; }
};
class C: public A
{ public:
C( ) { cout<<“Constructor C”; }
};
int main()
{ B b1;
C c1;
}
Hybrid Inheritance
• Hybrid Inheritance is implemented by combining more
than one type of inheritance.
• For example: Combining Hierarchical inheritance and
Multiple Inheritance.
class A
{ public:
A( ) { cout<<“Constructor A”; }
};
class B
{ public:
B( ) { cout<<“Constructor B”; }
int main()
};
{
class C: public A C c1;
{ public: D d1;
C( ) { cout<<“Constructor C”; } }
};
Class D: public A, public B
{ public:
D( ) { cout<<“Constructor D”; }
Multipath Inheritance
A derived class with two base classes and these two base
classes have one common base class is called multipath
inheritance.
Ambiguity in
multipath
inheritance
Ambiguity in multipath
inheritance
Ways to solve this ambiguity :

1. scope resolution operator ::


2. Virtual base class
class A
{
public: int a; int main()
{
};
class B: public A D d1;
{
public: int b; d1.B::a = 10;
}; d1.C::a = 100;
d1.b = 20;
Class C: public A
d1.c = 30;
{ d1.d = 40;
public: int c; cout<<“a from B= “<<d1.B::a;
}; cout<<“a from B= “<<d1.B::a;
Class D: public B, public C cout<<“b= “<<d1.b;
cout<<“c= “<<d1.c;
{
cout<<“d= “<<d1.d;
public: int d; }
Virtual Base Class
To resolve multipath 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.

Syntax 1: Syntax 2:

class B : virtual public A class C : public virtual A


{ {

}; };
class A
{
public: int a; int main()
{
};
class B: virtual public A D d1;
{
public: int b; d1.a = 10;
}; d1.b = 20;
d1.c = 30;
Class C: virtual public A
d1.d = 40;
{ cout<<“a = “<<d1.a;
public: int c; cout<<“b = “<<d1.b;
}; cout<<“c = “<<d1.c;
Class D: public B, public C cout<<“d = “<<d1.d;
}
{
public: int d;
Function Overloading
• When there are multiple functions with same name
but different parameters then these functions are
said to be overloaded.
• Functions can be overloaded by change in number
of arguments or/and change in type of arguments.
• Return type and parameters are different but
function name remains same.
#include<iostream>
using namespace std;
class A
{
int a=10;
public:
int main()
void display()
{
{ A a1;
cout<<a<<endl; a1.display();
} a1.display(20);
void display(int b) return 0;
}
{
cout<<b<<endl;
}
};
Function overriding
• Function overriding is a feature that allows us to
have a same function in derived class which is
already present in the base class.
• It is like creating a new version of an old function, in
the child class.
• When you call the function which is present in both
base and child class, child class function is invoked.
• The function of base class is ignored.
class Base
{ public:
void display() //overridden function
{ cout<<“Function in base class”;}
};
class Derived: public Base
{ public:
void display() //overriding function
{ cout<<“Function in derived class;}
};
int main()
{ Derived d;
d.display(); }
Access overridden function
• To access the overridden function of the base class,
we use the scope resolution operator ::

• We can also access the overridden function by using


a pointer of the base class to point to an object of the
derived class and then calling the function from that
pointer
class Base using :: in main()
{ public:
void display() //overridden function
{ cout<<“Function in parent class”;}
};
class Derived: public Base
{ public:
void display() //overriding function
{ cout<<“Function in Base class; }
};
int main()
{ Derived d;
d.display();
d.Base::display();
}
class Base using :: operator
{ public:
void display() //overridden function
{ cout<<“Function in parent class”;}
};
class Derived: public Base
{ public:
void display() //overriding function
{ cout<<“Function in Base class;
Base :: display(); }
};
int main()
{ Derived d;
d.display(); }
Function Overloading Function Overriding

Function Overloading provides multiple Function Overriding is the redefinition of


definitions of the function by changing base class function in its derived class
signature. with same signature.

An example of compile time


An example of run time polymorphism.
polymorphism.

Function signatures should be different. Function signatures should be the same.

Overridden functions are in different


Overloaded functions are in same scope.
scopes.

Overloading is used when the same


Overriding is needed when derived class
function has to behave differently
function has to do some different job than
depending upon parameters passed to
the base class function.
them.

In function overloading, we don’t need In function overriding, we need an


inheritance. inheritance concept.
Pure Virtual Function
• A pure virtual function in C++ is a function for
which we do not have an implementation.
• We only declare this function in base class and
derive classes must have implementation of it.
• A pure virtual function is declared by assigning
a zero (0) in its declaration.
• Syntax:
virtual <return_type> <function_name>() = 0;
Class shape
{ public:
virtual void draw()=0;
};
int main()
class circle: public shape {
{ public:
void draw(){ } circle c;
c.draw();
};
square s;
class square: public shape s.draw();
{ public:
void draw(){ } }
};
Abstract Class
• A base class which contains at least one pure
virtual function.

• We cannot create objects of abstract classes.

• If we do not override the pure virtual function in


the derived class, then the derived class also
becomes an abstract class.
Friend Class

• A friend class can access private and protected


members of other classes in which it is declared as a
friend.
• To access the members of a class, it must use the
object of that class.
• Syntax:
friend class class_name;
Nested Class
• A nested class is a class declared in another class.
• Nested class can access private members of the
main class.
• But main class can not access private members of
nested class.
SMT KASHIBAI NAWALE COLLEGE OF
ENGINEERING
Department of Computer Engineering

Inheritance and Pointers


Pointers: Declaring and initializing pointers, indirection operators,
memory management: new and delete, pointers to objects, this
pointer, pointers vs arrays, accessing arrays using pointers, array of
pointers, function pointers, pointers to pointers, pointers to derived
classes, passing pointers to functions, return pointers from
functions, null pointer, void pointer.
Pointers
• Pointer is a variable whose value is the address of
another variable.
• Unlike normal variable which stores a value (such
as an int, a double, a char), a pointer stores a
memory address.
Declaring a Pointer
• Pointers must be declared before they can be used,
just like a normal variable.
• The syntax of declaring a pointer is to place a * in
front of the name.
• A pointer is associated with a type (such as int and
double) too.
• Syntax:
datatype *ptr_name;
OR
datatype* ptr_name;
Declaring a Pointer
• Example:
int *ip;
double *dp;
float *fp;
char *ch;
• Actual data type of the value of all pointers is same,
a long hexadecimal number that represents a
memory address.
• The reason we associate data type to pointer is that it
knows how many bytes the data is stored in.
Pointer Operator

1. Address of operator (&)

2. Indirection operator (*)


Address of (&)
• It is a unary operator that returns the memory
address of its operand.
• It is spelled as the address of the variable.
• Example:
int a;
int *p;
p = &a; //referencing
Indirection operator (*)
• Also called as dereference operator.
• It is a unary operator that returns the value
of the variable present at the given address.
• It is completely opposite to the address-of
operator.
• It is spelled as a value pointed at the
address.
Indirection operator (*)
Arithmetic Operations on Pointers

1. Incrementing and Decrementing Pointers


2. Addition of Constant to Pointers
3. Subtraction of Constant from Pointers
4. Subtraction of Two Pointers of the Same
Type
5. Comparison of Pointers
1. Incrementing and Decrementing
Pointers
• Incrementing or decrementing a pointer will
make it refer to the address of the next or
previous data in the memory.
• This process differs from incrementing and
decrementing numeric data.
• Address increases or decreases by 1
multiplied by the size of the data type it is
pointing to
1. Incrementing and Decrementing
Pointers
2. Addition of Constant to Pointers

We can add integer values to Pointers and the


pointer is adjusted based on the size of the data
type it points to.
3. Subtraction of Constant from
Pointers
We can also subtract a constant from Pointers and
it is the same as the addition of a constant to a
pointer.
4. Subtraction of Two Pointers of
the Same Data type
• The Subtraction of two pointers can be done
only when both pointers are of the same data
type.
• The subtraction of two pointers gives the
number of elements present between the two
pointers.
5. Comparison of Pointers

• In C++, we can perform a comparison


between the two pointers using the relational
operators(>, <, >=, <=, ==, !=).
• We generally use this operation to check
whether the two-pointer are pointing to the
same memory location or not.
Features of Pointers
• Pointers save memory space.
• Execution time with pointers is faster because
data are manipulated with the address.
• Pointers are used to allocate memory
dynamically.
• Pointers are used for file handling.
Drawbacks of Pointers
• If pointers are pointed to some incorrect
location then it may end up reading a wrong
value.
• Erroneous input always leads to an erroneous
output.
• If we forgot to deallocate a memory then it
will lead to a memory leak.
Memory Management

• Memory Allocation : reserving memory for


variables, arrays, objects, etc.
• When we create variables or objects,
memory is allocated to them.
• Types:
1. Static memory allocation
2. Dynamic memory allocation
Static memory allocation
• Allocating fixed amount of memory for data at
starting of the program or function.
• Drawbacks:
– Allocated memory can be larger, resulting in wastage
of memory
– Allocated memory can be lesser, resulting in program
failure.
– One can’t clean up or release memory when not
required.
Dynamic Memory Allocation

• Size of memory is decided according to


program/user requirements.
• Memory can be allocated or de-allocated at any
stage of program.
• Dynamic memory allocation uses pointers.
• Keyword new is used to allocate a memory and
delete to free a memory.
Static vs Dynamic
The main differences between static allocation
and dynamic allocations are:
• In static allocation, the compiler allocates and
deallocates the storage automatically, and handle
memory management.
• Whereas in dynamic allocation, the programmer,
handle the memory allocation and deallocation (via
new and delete operators).
new
• Allocating memory to one variable/object:
pointer-variable = new data-type;

• Allocation memory to array


pointer-variable = new data-type[size];

• the pointer variable is the pointer of type data-type.


• Data type could be any built-in or user defined data
type.
delete
• De-allocating memory to one variable/object:
delete pointer-variable;

• De-allocation memory to array


delete pointer-variable[];
#include <iostream>
using namespace std;
int main()
{
int *ptr1 = new int;
*ptr1 = 5;
float *ptr2 = new float(20.324);

cout << "Value of pointer variable 1 : " << *ptr1 << endl;
cout << "Value of pointer variable 2 : " << *ptr2 << endl;

delete ptr1;
delete ptr2;
return 0;
}
Pointers to Objects
• Pointers to objects aim to make a pointer that can
access the object, not the variables.
• Pointer to object in C++ refers to accessing an
object.
• It stores the address of an object.
• There are two approaches by which you can
access members of class.
• One is using simple object and the other is by
using a pointer to an object in C++.
Pointers to Objects
• Syntax:
classname objectname;
classname *pointer_to_object;
pointer_to_object = &objectname;

After storing the address in the pointer to the object,


the member function can be called using the pointer
to the object with the help of an arrow operator.
Pointers to Objects
#include <iostream>
using namespace std;
class MyClass
{
public:
void myFunction()
{
cout << "Hello from MyClass!" << endl;
}
};
Pointers to Objects
int main()
{
MyClass obj; // Create an object of MyClass
MyClass *ptr; //Create pointer of MyClass

ptr = &obj; // Create a pointer to the object


ptr -> myFunction(); // Access functions using the ptr

return 0;
}
Pointer to Derived Class

• Pointers can be used for base objects as well as


objects of derived classes.
• Base class pointer can only access all members of
base class.
• To access derived class’s members, you need to
create derived class pointer.
• Using derived class pointer, we can access base
class’s members.
this Pointer
• Every object in C++ has access to its own address
through an important pointer called this pointer.
• The this pointer is an implicit parameter to all
member functions.
• It is used to refer to the invoking object.
• Static and Friend functions do not have a this pointer.
• The this pointer holds the address of current object, in
simple words you can say that this pointer points to
the current object of the class.
When local variable’s name is
same as member’s name
class Demo
{ int x;
int main()
public:
{
void setValues(int x)
Demo d;
{
d.setValues(100);
this->x = x;
d.print();
}
return 0;
void print()
}
{ cout << x;}
};
Pointer vs Arrays

• An array is a data structure that represents a


collection of elements of the same type stored in
contiguous memory locations.
• It provides a way to store and access multiple values
of the same data type using a single variable.
• A pointer is a variable that holds the memory
address of another variable.
• Pointers can be used to access array elements
Pointer Array
It is declared as -: It is declared as -:
data_type *var_name; data_type var_name[size];
It is a variable that stores the It is the collection of elements of
address of another variable. the same data type.
We can create a pointer to an array. We can create an array of pointers.
A pointer variable can store the An array can store a number of
address of only one variable at a elements the same size as the size
time. of the array variable.
Pointer allocation is done during Array allocation is done during
runtime. compile runtime.
The nature of pointers is dynamic The nature of arrays is static, the
means the memory can be allocated size of an array cannot be resized
or freed at any point in time. according to user requirements.
Accessing Arrays using pointers

int *ptr;
int arr[5];
ptr = arr; // store the address of the first
// element of arr in ptr
OR
int *ptr;
int arr[3]={1,2,3};
ptr = &arr[0];
cout<<*ptr;
Accessing Arrays using pointers
Array of pointer
• An array of pointers is an array of pointer variables.
• We can declare a pointer that can point to whole array
instead of only one element of an array.
• Syntax:
dataType (*pointer_name) [size];
• Example:
int (*ptr)[3]; // array of pointers
int a[3]={1,2,3}; // array of integer
ptr = &a; // ptr points to whole array a
cout<<*(ptr[0]); // 1
Function pointer

• The function pointer is used to point functions.


• It is utilized to save a function’s address.
• The function pointer is either used to call the
function or it can be sent as an argument to
another function.
Function pointer

Syntax:
• Declaring
return_type (*FuncPtr) (parameter type, ....);

• Referencing
FuncPtr = function_name;

• Dereferencing
data_type x = *FuncPtr;
Function pointer used to call the
function
#include <iostream>
using namespace std;
int multiply(int a, int b) { return a * b; }
int main()
{
int (*fp)(int, int);
fp = multiply;
int product = fp(15, 2);
cout << "The value of the product is: " << product;
return 0;
}
Pointer to Pointer

• When we define a pointer to a pointer, the first


pointer is used to store the address of the variables
• The second pointer stores the address of the first
pointer.
• This is also known as a Double Pointer
Pointer to Pointer

• Syntax:

data_type **name_of_pointer2 = &pointer1;

• Example:
int var = 10;
int *ptr1 = &var;
int **ptr2 = &ptr1;
Pointer to Pointer
Passing parameters to Function

1. Pass by value
2. Pass by reference
3. Pass by Pointer
Pass by Value

• When you call a function with pass by value, two


copies of variables with the same value are
created.
• In effect, whatever changes are made to the
variables inside the called function are not
reflected to the actual variables with which the
function is called.
Pass by Value.. Example
void doubleTheValue(int a)
{
a = a*2;
}
int main()
{
int a = 5;
cout << “Initial value of a = " << a << "\n";
doubleTheValue(a);
cout << "Final Value of a = " << a << "\n";
}
Pass by Reference

• Here, we pass the memory location of the


variable to the called function.
• That means, both the passed variable and the
parameter used in the called function point to the
same location
• Any changes to the parameter reflects in the
variable as well.
Pass by Reference.. Example
void doubleTheValue(int &p)
{
p = p*2;
}
int main()
{
int a = 5;
cout << “Initial value of a = " << a << "\n";
doubleTheValue(a);
cout << "Final Value of a = " << a << "\n";
}
Pass by Pointer
(Passing Pointers to function)
• In our previous example of doubleTheValue
function, we are passing the value of ‘a’ by
reference using ‘&’.
• We can do the same thing by passing the value
through a pointer.
• The output is the same whether we do pass by
pointer or pass by reference.
Pass by Pointer.. Example

void doubleTheValue(int *ptr)


{
*ptr = (*ptr)*2;
cout << "Address of a (ptr) = " << ptr << "\n";
}
int main()
{
int a = 5;
cout << "Initial value of a = " << a << "\n";
doubleTheValue(&a);
cout << "Final Value of a = " << a << "\n";
}
Return pointer from function
• C++ allows to pass pointers to the function as well
as return a pointer from a function.
• This can be achieved by declaring the return type of
the function as a pointer.
• Syntax:
pointer_return_type function_name(parameters)
{ statements; }

• Example:
int * MyFunction() { statements; }
Return pointer from function
int global_var = 25;
int * MyFunction() { return &global_var; }
int main ()
{
int a=20;
int *p = &a;
cout<<“Before: “<<*p<<"\n";
p = MyFunction();
cout<<“After: “<<*p<<"\n";
return 0;
}
Null Pointer
• The NULL is a constant with a value of zero
defined in several standard libraries, including
iostream.
• Assign the value 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.
Null Pointer
#include <iostream>
using namespace std;
int main ()
{
int *ptr = NULL;
cout << "The value of ptr is " << ptr ;
return 0;
}
Void Pointer

• A void pointer is a pointer that has no associated


data type with it.
• A void pointer can hold an address of any type and
can be type casted to any type.
• But void pointers cannot be dereferenced.
Void Pointer
int main()
{
int a = 10;
void* ptr = &a;

cout << *ptr; // will give error

cout << *(int*)ptr << endl;


return 0;
}
Important topics
• This pointer
• Dynamic memory allocation – new and
delete
• Function pointer
• Arrays using pointer
• Pointers to base class and derived class
• Null pointer and void pointer

You might also like