Unit II - Inheritance & Pointers Final

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 68

Unit II: Inheritance & Pointers

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.

Pointers: declaring and initializing pointers, indirection Operators, Memory


Management: new and delete, Pointers to Objects, this pointer, Pointers Vs Arrays,
accessing Arrays using pointers, Arrays of Pointers, Function pointers, Pointers to Pointers,
Pointers to Derived classes, Passing pointers to functions, Return pointers from functions,
Null pointer, void pointer.
Inheritance

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

Sub class or Derived Class or child :


The class that inherits properties from another class
Super Class OR base class Or parent :
The class whose properties are inherited by sub class
Class BaseClass
{
//BaseClass properties and functions
};

class DerivedClass : accessSpecifier BaseClass


{

};
Access specifier can be public, protected and private.
The default access specifier is private.
Inheritance

Access Specifiers or Visibility mode of inheritance

Public - members are accessible from outside the class


Private - members cannot be accessed (or viewed) from outside the class
Protected - members cannot be accessed from outside the class, however, they can be
accessed from inherited classes.
Access Within same In derived Outside
Specifier class class the class

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

// class_C inheriting class_A and


#include <iostream> // class_B
class_B
using namespace std; class Computer
class Linux_based : public
// base class {
electronicDevice, public Computer
class electronicDevice public:
{};
{ // constructor of the base class 2
public: Computer()
int main()
// constructor of the base {
{
class electronicDevice() cout << "I am a computer.\n\n";
// create object of the derived class
{ }
Computer obj;
cout << "I am an electronic device.\
};
// constructor of base class and
n\n";
derived class will be called
}
return 0;
};
}
Ambiguity in Multiple Inheritance

 In multiple inheritance, a single class is derived from two or more parent


classes. So, there may be a possibility that two or more parents have
same named member function.

 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

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


}
Constructor and destructor in Derived Class

 Base class constructors are called first and the derived class constructors
are called next in single inheritance.

 The constructor of base class is called first to initialize all the


inherited members.

 Destructor is called in reverse sequence of constructor invocation i.e.


The destructor of the derived class is called first and the destructor of the
base is called next.
Order of calling Constructors and Destructors in Inheritance
Order of calling Constructors and Destructors in Inheritance
#include<iostream> class Derived:public Base
using namespace std; {
class Base public:
{
Derived()
public:
Base() {
{ cout<<“\nderived class
cout<<“\nbase class constructor"; constructor”;
} }
~Base() ~Derived()
{ {
cout<<“\nbase class destructor“; cout<<“\nderived class
} destructor";
};
}
};
int main()
{
Derived d;
}
Constructor and destructor in Derived Class

• 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

class Derived:public Base2,public Base1 int main()


{ {
Derived() Derived d;
{ }
cout<<"\nDerived constructor";
}

};
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;
};

class intermediate_classname:visibility_mode base_classname


{
properties;
methods;
};

class child_classname:visibility_mode intermediate_classname


{
properties;
methods;
};
Hierarchical Inheritance

 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

1.#include <iostream> 1.class B : public A //


B is derived from class base 1.int main()
2.using namespace std;
2.{ 2.{
3.class A // Base class 3. //object of derived class B
3.public:
4. { 4.void product() 4. B obj1;
5.public: 5. { 5. //object of derived class C
6.int x, y; // data members 6.cout<< "\ 6. C obj2;
7.voidgetdata() // to input x and y nProduct= " << x * y <<endl; // Perfo 7.obj1.getdata(); // input x and y
8. { rm product 8.obj1.product();
9.cout<< "Enter value of x and y:\ 7. } 9.obj2.getdata();
n"; 8.}; 10.obj2.sum();
9.class C : public A // 11.return 0;
10.cin>> x >> y;
C is also derived from class base 12.}
11. }
10.{
12.} 11.public:
12.void sum()
13. {
14.cout<< "\
nSum= " << x + y; // Perform sum
15. }
16.};
Hybrid 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

#include <iostream> // base class 2


// derived class 2 inheriting derived
using namespace std; class Computer
class 1
// base class 1 {
class Debian: public Linux_based
class electronicDevice public:
{
{ // constructor of the base class 2
public: Computer()
};
{
// constructor of the base class
cout << "I am a computer.\n\
1 Int main()
n";
electronicDevice() {
}
{ // create an object of the derived
};
class
cout << "I am an electronic // derived class 1 inheriting base
Debian obj; // constructor of base
device.\n\n"; class 1 and base class 2
classes and derived class will be
} called
}; class Linux_based : public
return 0;
electronicDevice, public
}
Computer
{

};
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.
Overriding Member Functions

Function overriding in C++ is a feature that allows us to use


a function in the child class that is already present in its
parent class.
Requirements for Overriding a Function :
 Inheritance should be there.
- Function overriding cannot be done within a class. For this we
require a derived class and a base class.

 Function that is redefined must have exactly same signature in both


base and derived class, that means same name, same return type and
same list of parameters.
Overriding Member Functions

• Derived class object will invoke the


derived class function.
• How to access the overridden function
of the base class??
First Solution

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

Invoke the base class function


from the derived class
function using base class
name and scope resolution
operator.
Virtual Base Class

 When two or more objects are derived from a common base


class, we can prevent multiple copies of the base class being
present in an object derived from those objects by declaring the
base class as virtual when it is being inherited.

 Such a base class is known as virtual base class. This can be


achieved by preceding the base class’ name with the word virtual.
Virtual Base Class
 Need for Virtual Base Classes:
Consider the situation where we
have one class A .This class is A is
inherited by two other
classes B and C. Both these class are
inherited into another in a new
class D as shown in figure below.

 Need for Virtual Base Classes:


As we can see from the figure that
data members/function of
When any data / function member of class A is accessed
class A are inherited twice to
by an object of class D, ambiguity arises as to which
data/function member would be called? One inherited class D. One through class B and
through B or the other inherited through C. This second through class C.
confuses compiler and it displays error.
Virtual Base Class - Example

class B class D3 : public D1, public D2


{ {
public: public: int d3;
int b; };
};
int main()
class D1 : public B {
{ D3 obj;
public: int d1;
}; obj.b = 40; /*error will occur as
multiple copies of variable b are
class D2 : public B present in class D3*/
{
public: int d2; }
};
Virtual Base Class - Example

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

class B class D3 : public D1, public D2


{ {
public: public: int d3;
int b; };
};
int main()
class D1 : virtual public B {
{ D3 obj;
public: int d1;
}; obj.b = 40; /* no error */

class D2 : public virtual B }


{
public: int d2;
};
Abstract Classes
 An abstract class is one that is not used to create objects

 An abstract class is designed to act as a base class(to be inherited by other class).

 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.

 The members of an enclosing class have no special access to members of a


nested class; the usual access rules shall be obeyed.

 Example:
class Outer
{
class Inner
{
};
};
Nested Class

class A //enclosing class void A::print()


{ {
int a;
public: cout<<“\na:”<<a;
class B //nested class }
{ int main()
int b; {
public:
void setdata(A &obj) cout<<"Nested classes in C++";
{ A a1;
obj.a = 10; A :: B b1;
}
}; b1.setdata(a1);
void print(); a1.print();
}; return 0;
}
Syllabus

• Pointers: declaring and initializing pointers, indirection


Operators, Memory Management: new and delete, Pointers to
Objects, this pointer, Pointers Vs Arrays, accessing Arrays
using pointers, Arrays of Pointers, Function pointers, Pointers
to Pointers, Pointers to Derived classes, Passing pointers to
functions, Return pointers from functions, Null pointer, void
pointer.
Pointers

Normal variable is used to store the value.


A pointer is a variable that holds the address of another variable.
Pointers are symbolic representations of addresses.
We can have pointer to any variable type.

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

 Reference operator (&) and Deference operator (*)


 Reference operator (&) gives the address of a variable.
 To get the value stored in the memory address, we use the dereference operator (*)
which is also called as indirection operator.
Pointer Declaration

type *ptr; // Declare a pointer variable called ptr as a pointer of type


// or
type* ptr;
// or
type * ptr;
int * iPtr; // Declare a pointer variable called iPtr pointing to an int (an int pointer).
//It contains an address. That address holds an int value.

double * dPtr; // Declare a double pointer

The * in the declaration statement is not an operator, but indicates that the name followed is a
pointer variable.
For example,

int *p1, *p2, i; // p1 and p2 are int pointers. i is an int


int* p1, p2, i; // p1 is a int pointer, p2 and i are int
int * p1, * p2, i; // p1 and p2 are int pointers, i is an int
Pointer Declaration

e.g.
If a number variable is stored
in the memory address 0x123,
and it contains a value 5.

The reference (&) operator


gives the value 0x123, while
the dereference (*) operator
gives the value 5.
Memory Management

 Two operators new and delete that perform the task of allocating and freeing the memory in a
better and easier way.

syntax of new operator:


pointer_variable = new datatype; *P=0x1002
int *p=new int;

syntax to initialize the memory : 10


pointer_variable = new datatype(value);
0x1002
int *p=new int(10);

syntax to allocate a block of memory,


pointer_variable = new datatype[size];
int *p=new int[5];
Memory Management

syntax of delete operator :


delete pointer_variable;

syntax to delete the block of allocated memory:

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.

Syntax: Class_name ∗object_pointer ;


class_name obj1,*obj2;
obj2=&obj1

int var;  class_name obj;


int *p;  class_name *objp;
P=&var  objp=&obj
‘this’ Pointers

 Each object gets its own copy of data members.


 All objects share a single copy of member functions.

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

int *ptr; int *ptr;


int arr[5]; int arr[5];
// store the address of the first element of arr in ptr // store the address of the first element of arr in ptr
ptr = arr; ptr = &arr[0];

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

Syntax for Declaration int (*FuncPtr) (int,int);

return type Pointer name Parameter list

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

Output:- Address of a main() function is : 1 4)Assigned to other function


pointers
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
 first pointer contains the address of the second pointer,
 which points to the location that contains the actual value

Declaration Syntax:-
int **var;
Pointers to Pointers
int main () {
int var;
int *ptr;
int **pptr; Output:-

var = 3000; Value of var :3000


Value available at *ptr :3000
// take the address of var Value available at **pptr :3000
ptr = &var;

// take the address of ptr using address of operator &


pptr = &ptr;

// take the value using pptr


cout << "Value of var :" << var << endl;
cout << "Value available at *ptr :" << *ptr << endl;
cout << "Value available at **pptr :" << **pptr << endl;

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

Besides memory addresses, there is one additional value that a pointer


can hold: a null value.
A null value is a special value that means the pointer is not pointing at
anything.
A pointer holding a null value is called a null pointer.
#include <iostream>
using namespace std;
int main () Output :
{ ptr value = 0
int *ptr = NULL;
cout << “ptr value = " << ptr ;
return 0;
}
Void pointer
It holds the address of any data type, but it is not associated with any data type.
Syntax :
void *ptr;
The size of void pointer varies system to system.
 16 bit system it is 16-bit.
 32 bit system, it is 32-bit
 64 bit system the size is 64-bit.
In C++, you cannot assign the address of variable of one type to a pointer of
another type.
e.g.
int *ptr;
double d = 9;
ptr = &d; // Error: can't assign double* to int*
To avoid it, make use of general purpose pointer i.e. void pointer.
Void pointer
#include <iostream>
using namespace std;
int main() Output :
{ 0xffd117ac
0xffd117ac
void* ptr; 2.3
float f = 2.3;
ptr = &f;
cout << &f << endl;
cout<<ptr;
cout<<*((float*)ptr);
return 0;
}

You might also like