Monday, February 15, 2016

C++ POINTERS

C++ POINTERS

Pointers are the powerful feature of C++ programming which differs it from other popular programming languages like: Java, Visual Basic etc.
To understand pointers, you should have the knowledge of address in computer memory. Computer memory is broken down into bytes and each byte has its own address. For example: In 1KB memory, there are 1024 bytes and each byte is given an address (0 - 1023).

The Address-of Operator &

The & operator can find address occupied by a variable. If var is a variable then, &vargives the address of that variable.

Example 1: Address-of Operator

#include <iostream>
using namespace std;

int main() {
    int var1 = 3;
    int var2 = 24;
    int var3 = 17;
    cout<<&var1<<endl;
    cout<<&var2<<endl;
    cout<<&var3<<endl;

}
Output
0x7fff5fbff8ac
0x7fff5fbff8a8
0x7fff5fbff8a4
The 0x in the beginning represents the address is in hexadecimal form. (You may not get the same result on your system.). Notice that first address differs from second by 4-bytes and second address differs from third by 4-bytes. It is because the size of integer(variable of type int) is 4 bytes in 64-bit system.

Pointers Variables

Now you know about address in computer memory, it's time to learn about pointers.
Consider a normal variable as in above example, these variables holds data. But pointer variables or simply pointers are the special types of variable that holds memory address instead of data.

How to declare a pointer?

int *p;
      OR,
int* p;
The statement above defines a pointer variable p. The pointer p holds the memory address. The asterisk is a dereference operator which means pointer to. Here pointer pis a pointer to int, that is, it is pointing an integer.
Note: In above statement p is a pointer variable that holds address not *p. The *pis an expression. The content(value) of the memory address pointer p holds is given by expression *p.

Example 2: C++ Pointers

C++ Program to demonstrate the working of pointer.

#include <iostream>
using namespace std;
int main() 
{
 int *pc, c;
 c = 5;
 cout<< "Address of c (&c): " << &c << endl;
 cout<< "Value of c (c): " << c << endl << endl;
 pc = &c;// Pointer pc holds the memory address of variable c
 cout<< "Address that pointer pc holds (pc): "<< pc << endl;
 cout<< "Content of the address pointer pc holds (*pc): " 
 cout<<*pc << endl << endl;
 c = 11;//The content inside memory is changed from 5 to 11.
 cout << "Address pointer pc holds (pc): " << pc << endl;
 cout << "Content of the address pointer pc holds (*pc): " 
 cout<<*pc << endl << endl;
 *pc = 2; 
 cout<< "Address of c (&c): "<< &c <<endl;
 cout<<"Value of c (c): "<< c<<endl<< endl;

    return 0;
}
Output
Address of c (&c): 0x7fff5fbff80c
Value of c (c): 5

Address that pointer pc holds (pc): 0x7fff5fbff80c
Content of the address pointer pc holds (*pc): 5

Address pointer pc holds (pc): 0x7fff5fbff80c
Content of the address pointer pc holds (*pc): 11

Address of c (&c): 0x7fff5fbff80c
Value of c (c): 2

Working of pointer in C++ programming
Arithmetic Operations on Pointers
As you understood pointer is an address which is a numeric value; therefore, you can perform arithmetic operations on a pointer just as you can a numeric value. There are four arithmetic operators that can be used on pointers: ++, --, +, and -
To understand pointer arithmetic, let us consider that ptr is an integer pointer which points to the address 1000. Assuming 32-bit integers, let us perform the following arithmatic operation on the pointer:
ptr++
the ptr will point to the location 1004 because each time ptr is incremented, it will point to the next integer. This operation will move the pointer to next memory location without impacting actual value at the memory location. If ptr points to a character whose address is 1000, then above operation will point to the location 1001 because next character will be available at 1001.

Incrementing a Pointer:

We prefer using a pointer in our program instead of an array because the variable pointer can be incremented, unlike the array name which cannot be incremented because it is a constant pointer. The following program increments the variable pointer to access each succeeding element of the array:
#include <iostream>

using namespace std;
const int MAX = 3;

int main ()
{
   int  var[MAX] = {10, 100, 200};
   int  *ptr;

   // let us have array address in pointer.
   ptr = var;
   for (int i = 0; i < MAX; i++)
   {
      cout << "Address of var[" << i << "] = ";
      cout << ptr << endl;

      cout << "Value of var[" << i << "] = ";
      cout << *ptr << endl;

      // point to the next location
      ptr++;
   }
   return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Address of var[0] = 0xbfa088b0
Value of var[0] = 10
Address of var[1] = 0xbfa088b4
Value of var[1] = 100
Address of var[2] = 0xbfa088b8
Value of var[2] = 200

Decrementing a Pointer:

The same considerations apply to decrementing a pointer, which decreases its value by the number of bytes of its data type as shown below:
#include <iostream>

using namespace std;
const int MAX = 3;

int main ()
{
   int  var[MAX] = {10, 100, 200};
   int  *ptr;

   // let us have address of the last element in pointer.
   ptr = &var[MAX-1];
   for (int i = MAX; i > 0; i--)
   {
      cout << "Address of var[" << i << "] = ";
      cout << ptr << endl;

      cout << "Value of var[" << i << "] = ";
      cout << *ptr << endl;

      // point to the previous location
      ptr--;
   }
   return 0;
}
When the above code is compiled and executed, it produces result something as follows:
Address of var[3] = 0xbfdb70f8
Value of var[3] = 200
Address of var[2] = 0xbfdb70f4
Value of var[2] = 100
Address of var[1] = 0xbfdb70f0
Value of var[1] = 10


C++ Pointers and Arrays

Pointers are the variables that hold address. Pointers can point at cells of an array not only single variable. Consider this example:
int* ptr;
int a[5];
ptr = &a[2];//&a[2] is the address of third element of a[5]
C++ Program to display address of elements of an array using both array and pointers
#include <iostream>
using namespace std;

int main() {
    float a[5];
    float *ptr;
    
    cout << "Displaying address using arrays: "<<endl;
    for (int i = 0; i < 5; ++i) {
        cout << "&a[" << i << "] = " << &a[i] <<endl;
    }

    ptr = a;   // ptr = &a[0]
    cout<<"\nDisplaying address using pointers: "<< endl;
    for (int i = 0; i < 5; ++i) {
        cout << "ptr + " << i << " = "<<ptr+i <<endl;
    }

    return 0;
}
Output
Displaying address using arrays: 
&a[0] = 0x7fff5fbff880
&a[1] = 0x7fff5fbff884
&a[2] = 0x7fff5fbff888
&a[3] = 0x7fff5fbff88c
&a[4] = 0x7fff5fbff890

Displaying address using pointers: 
ptr + 0 = 0x7fff5fbff880
ptr + 1 = 0x7fff5fbff884
ptr + 2 = 0x7fff5fbff888
ptr + 3 = 0x7fff5fbff88c
ptr + 4 = 0x7fff5fbff890#include <iostream.h> 
Pointers to Objects:
     A variable that holds an address value is called  a pointer variable or simply pointer. Pointer can point to objects as well as to simple data types and arrays. sometimes we dont know, at the time that we write the program , how many objects we want to create. when this is the case we can use new to create  objects while the program is running. new returns a pointer to an unnamed objects.
Example:
#include<iostream.h>
class item
{
int code;
float price;
public:
void getdata(int a, float b)
{
code =a;
price=b;
}
void show(void)
{
cout<<"code:"<<code<<"\n";
cout<<"Price:"<<price<<"\n";
}
};
const int size=2;
int main()
{
item *p = new item[size];
item *d = p;
int x,i;
float y;
for(i=0;i<size;i++)
{
cout<<"Input code and price for item"<<i+1;
cin>>x>>y;
p->getdata(x,y);
p++;
}
for(i=0;i<size;i++)
{
cout<<"Item:"<<i+1<<"\n";
d->show();
d++;
}
return 0;
}
Output:
 

CONSTRUCTORS IN DERIVED CLASSES

CONSTRUCTORS IN DERIVED CLASSES

     A constructor plays a vital role in initializing an object. An important note, while using constructors during inheritance, is that, as long as a base class constructor does not take any arguments, the derived class need not have a constructor function. However, if a base class contains a constructor with one or more arguments, then it is mandatory for the derived class to have a constructor and pass the arguments to the base class constructor. Remember, while applying inheritance, we usually create objects using derived class. Thus, it makes sense for the derived class to pass arguments to the base class constructor. When both the derived and base class contains constructors, the base constructor is executed first and then the constructor in the derived class is executed.

Example:
// program to show how constructors are invoked in derived class
#include <iostream.h>
class alpha
(
    private: 
        int x; 
    public: 
        alpha(int i)
        {
            x = i;
            cout << "\n alpha initialized \n";
        }
        void show_x()
        {
            cout << "\n x = "<<x;
        }
);
class beta
(
    private: 
        float y; 
    public: 
        beta(float j)
        {
            y = j;
            cout << "\n beta initialized \n";
        }
        void show_y()
        {
            cout << "\n y = "<<y;
        }
);
class gamma : public beta, public alpha
(
    private: 
        int n,m; 
    public: 
        gamma(int a, float b, int c, int d):: alpha(a), beta(b)
        {
            m = c;
            n = d;
            cout << "\n gamma initialized \n";
        }
        void show_mn()
        {
            cout << "\n m = "<<m;
            cout << "\n n = "<<n;
        }
);

void main()
{
    gamma g(5, 7.65, 30, 100);
    cout << "\n";
    g.show_x();
    g.show_y();
    g.show_mn();
}
Output:
beta initialized

alpha initialized

gamma initialized


x = 5
y = 7.65
m = 30
n = 100

VIRTUAL BASE CLASSES

VIRTUAL BASE CLASSES

     An ambiguity can arise when several paths exist to a class from the same base class. This means that a child class could have duplicate sets of members inherited from a single base class. C++ solves this issue by introducing a virtual base class. When a class is made virtual, necessary care is taken so that the duplication is avoided regardless of the number of paths that exist to the child class.



Example:
#include<iostream.h>
#include<conio.h>
 
class student
{
   int rno;
  public:
   void getnumber()
   {
              cout<<"Enter Roll No:";
              cin>>rno;
   }
   void putnumber()
   {
              cout<<"\n\n\tRoll No:"<<rno<<"\n";
   }
};
 
class test:virtual public student
{
  
  public:
   int part1,part2;
   void getmarks()
   {
              cout<<"Enter Marks\n";
              cout<<"Part1:";
              cin>>part1;
              cout<<"Part2:";
              cin>>part2;
   }
   void putmarks()
   {
              cout<<"\tMarks Obtained\n";
              cout<<"\n\tPart1:"<<part1;
              cout<<"\n\tPart2:"<<part2;
   }
};

class sports:public virtual student
{
 
  public:
    int score;
    void getscore()
    {
              cout<<"Enter Sports Score:";
              cin>>score;
    }
    void putscore()
    {
              cout<<"\n\tSports Score is:"<<score;
    }
};

class result:public test,public sports
{
    int total;
  public:
   void display()
   {
      total=part1+part2+score;
      putnumber();
      putmarks();
      putscore();
      cout<<"\n\tTotal Score:"<<total;
   }
};
 
void main()
{
   result obj;
   clrscr();
   obj.getnumber();
   obj.getmarks();
   obj.getscore();
   obj.display();
   getch();
}

Output:

Enter Roll No: 200
 Enter Marks
 Part1: 90
Part2: 80
Enter Sports Score: 80
 Roll No: 200
 Marks Obtained
Part1: 90
Part2: 80
Sports Score is: 80
 Total Score is: 250

HIERARCHICAL,MULTILEVEL AND HYBRID INHERITANCE

Hierarchical inheritance

In these inheritance , derived class inherits property of Base Class but in these inheritance only one Base Class and multiple derived class are involved. In the Below program Class A is Base Class and Class B ,Class C ,Class D are derived class.(As Per below Diagram).



Example:

#include<iostream.h>
#include<conio.h>

class A  //Base Class
{
    public:
    int a,b;
    void getnumber()
    {
    cout<<"\n\nEnter Number :::\t";
    cin>>a;
    }

};

class B : public A  //Derived Class 1
{
    public:
    void square()
    {
    getnumber();  //Call Base class property
    cout<<"\n\n\tSquare of the number :::\t"<<(a*a);
    cout<<"\n\n\t----------------------------------------------------";
    }
};

class C :public A //Derived Class 2
{
    public:
    void cube()
    {
    getnumber(); //Call Base class property
    cout<<"\n\n\tCube of the number :::\t"<<(a*a*a);
    cout<<"\n\n\t----------------------------------------------------";
    }
};

int main()
{
clrscr();

B b1;         //b1 is object of Derived class 1
b1.square();  //call member function of class B
C c1;         //c1 is object of Derived class 2
c1.cube();    //call member function of class C

getch();
}

OUTPUT





Multilevel Inheritance

When a class is derived from another derived class is called multilevel inheritance. It is implemented by defining at least three classes. In multilevel inheritance, there is one base class and the remaining two is derived class.


In the below program class bottom inherits property(member function) of class middle which is square() and class middle inherits property of class
top which is getdata().

Example:
#include<iostream.h>
#include<conio.h>
class top                       //base class
{
public :
int a;
void getdata()
{
cout<<"\n\nEnter first Number :::\t";
cin>>a;
}
void putdata()
{
cout<<"\nFirst Number Is :::\t"<<a;
}
};

//First level inheritance
class middle :public top      // class middle is derived_1
{
public:
int b;
void square()
{
getdata();
b=a*a;
cout<<"\n\nSquare Is :::"<<b;
}
};

//Second level inheritance
class bottom :public middle    // class bottom is derived_2
{
public:
int c;
void cube()
{
square();
c=b*a;
cout<<"\n\nCube :::\t"<<c;
}
};

int main()
{
clrscr();
bottom b1;
b1.cube();
getch();
}

OUTPUT




Hybrid Inheritance

Hybrid inheritance is combination of two or more inheritances such as single,multiple,multilevel or Hierarchical inheritances.


In the below program class B inherits property(member function) of class A which is base class and class D inherits property from class B and class C.

Example:
#include<iostream.h>
#include<conio.h>

class A     //Base class
{
public:
int l;
void len()
{
cout<<"\n\nLenght :::\t";  
cin>>l;                  //Lenght is enter by user      
}
};
class B :public A   //Inherits property of class A
{
public:
int b,c;
void l_into_b()  
{
len();
cout<<"\n\nBreadth :::\t";
cin>>b;                      //Breadth is enter by user
c=b*l;                       //c stores value of lenght * Breadth i.e. (l*b) .  
}
};

class C
{
public:
int h;
void height()
{
cout<<"\n\nHeight :::\t";
cin>>h;                  //Height is enter by user
}
};

//Hybrid Inheritance Level
class D:public B,public C
{
public:
int res;
void result()
{
l_into_b();
height();
res=h*c;                          //res stores value of c*h  where c=l*b and h is height which is enter by user
cout<<"\n\nResult (l*b*h) :::\t"<<res;
}
};

int main()
{
clrscr();
D d1;
d1.result();
getch();
}

Output: