top of page

Pointer and Reference in C++


1> what is deference between pointer and reference?

Pointer:

Pointer is variable which store the address of the another variable.

syntax: int *ptr;

Example:

int main()
{
	int val = 10;
	int *ptr = &a;
	cout << *ptr <<endl; //*ptr--> means value of that address.
} 

In above example ptr is pointer variable which store the address the val variable.


Reference:

when a value is declared as reference then it becomes a alternate name for existing variable.

Example:

int main()
{
	int val = 10;
	int &x = val;// Here x is declare as alternate name for val variable. 
}  
  • Reference can not be Null.

  • once a reference is created it can not be later made to reference another object.

  • A reference must be initialized when declered.

int &x; //Invalid

int a = 10;

int b = 20;

int &x = a;// Valid

int &x = b; //Invalid


when do we pass arguments by reference or pointer?

  1. To Modify local variables of the caller function.

  2. for passing large size argument.

  3. To avoid object slicing.

  4. To achieve run time polymorphism in a function.

You can have pointer to pointer offering extra level of indirection where as reference

only offer one level of indirection.


what is object slicing?

When a derived class object assign into a base class object then addition attribute of derived class object are sliced off to form the base class object.


#include <iostream>
using namespace std;
class Base
{
	protected:
 		int i;
	public:
 		Base(int a)  { i = a; }
 		virtual void display()
 		cout << "I am Base class object, i = " << i << endl;
};
class Derived : public Base
{
 	int j;
	public:
 		Derived(int a, int b) : Base(a) { j = b; }
 		virtual void display()
 		cout << "I am Derived class object, i = "<< i << ", j = " << j << endl;
};
// Global method, Base class object is passed by value
void somefunc (Base obj) //for avoid object slicing pass &obj
{
 	obj.display();
}
int main()
{
 	Base b(33);
 	Derived d(45, 54);
 	somefunc(b);
 	somefunc(d); // Object Slicing, the member j of d is sliced off
 	return 0;
}

For avoid the unexpected behavior (object slicing) we used the pointer or reference.

Object slicing doesn’t occur when pointers or references to objects are passed as function arguments since a pointer or reference of any type takes same amount of memory.


void somefunc (Base &obj)
{
 	obj.display();
}

















Comments


bottom of page