Pointer To Class-2
Pointer To Class-2
17/02/11
Declaration
List L1 ; List *ptr; ptr = &(List) L1; The last line may be written as ptr = &List(L1) ;
Example
#include<iostream.h> class List { private : int x,y ; public : void Setdata(int a, int b) { cout<<Enter number of items : cin>> a; cout<<Enter price of one item:; cin>>b;
Contd..
x = a; y = b; } void Display1() { cout<<Number of items =<<x<<endl ; } void Display2() { cout<<Price of each item = <<y<<endl; }
Contd..
void Display3() { cout<<Cost of<<x<<items at the rate of<<y<<per item =<<x*y<<endl; } };
Contd..
void main() { List L1; List *ptr; ptr = &(List) L1; int i , j ; (*ptr).Setdata(i, j); ptr -> Display1(); ptr -> Display2(); (*ptr) .Display3(); }
Contd..
void Setprice(int a, int b, int c) { x = a, y = b, z = c; } void Display2() { cout<<Price of item1 = <<x<<endl; cout<<Price of item2 = <<y<<endl; cout<<Price of item3 = <<z<<endl; } };
Contd..
void main() { List L1; List *ptr; ptr = &(List) L1; ptr -> Setprice(6,8,10); ptr -> Display1(); cout<<Price List 1<<endl; ptr -> Display2(); List L2; *ptr++;
Contd..
ptr -> Setprice(32,27,38) ; ptr -> Display1(); cout<< Price List 2<<endl; ptr->Display2(); }
#include<iostream.h> class List { private : int x, y, z ; public : List (int a, int b, int c) { x = a, y = b, z = c; }
Contd..
void Display() { cout<<Price of item1 = <<x<<endl; cout<<Price of item2 = <<y<<endl; cout<<Price of item3 = <<z<<endl; } };
Contd..
void main() { int n = 0; List L1(12, 15, 27); cout<< List<<++n<<endl; List *ptr = &L1; ptr -> Display(); cout << \n List<<++n<<\n; List L2 (30, 54, 60); ptr = & L2 ; (*ptr).Display(); }
Example
#include<iostream.h> Class Rect { int x, y; public: void Setsides (int L, int W) { x = L, y = W; }
Contd..
int Area() { return x*y ; } }; int main() { Rect R1, R2, R3;
Contd..
void (Rect :: *ptrSet)(int, int) = & Rect :: Setsides ; (R1.*ptrSet)(20,15) ; cout<<Area of R1=<<R1.Area()<<endl ; ( R2. *ptrSet)(20, 30); cout<<Area of R2=<<R2.Area()<<endl ; Rect *ptr3 = &R3; (ptr3 -> *ptrSet)(16,10); cout<<Area of R3=<<R3.Area()<<endl ; return 0 ; }
Next Day..
Accessing private data of an object through pointers The this pointer Static data members of a class Static function member of a class Dynamic memory management for class objects