-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpointer_to_object.cpp
55 lines (49 loc) · 1.21 KB
/
pointer_to_object.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
// Create object in Stack or Heap
// Stack:
// Rectangle r1; // Valid
// Rectangle r1( ); // invalid, don’t give empty brackets.
// Heap:
// Rectangle *p; // pointer, it is created in stack.
// p=new Rectangle(); // object is created in heap. Empty () can be
// given.
// Pointer size
// Every pointer takes 8 bytes of memory in latest compiler.
// Size of pointer is not dependent on its datatype.
// Note: I have assumed that pointer takes 2 bytes, to make explanation
// easy
// '->' vs '.'
// Stack: if an object is created in stack, use ‘.’
// Rectangle r1;
// r1.area();
// Heap: if an object is created in heap then use ‘->’
// Rectangle *p;
// p=new Rectangle();
// p->area();
#include <iostream>
using namespace std;
/*program for writing pointer to an object
*/
class rectangle
{
public:
int length;
int breadth;
int area()
{
return length * breadth;
}
int perimeter()
{
return 2 * (length + breadth);
}
};
int main()
{
rectangle r1;
rectangle *ptr; // or we can say rectangle *ptr=new rectangle();
ptr = &r1; // instead of these two lines
ptr->length = 10;
ptr->breadth = 5;
cout << ptr->area() << endl;
cout << ptr->perimeter() << endl;
}