-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path47ptr_to_object.cpp
More file actions
53 lines (44 loc) · 1.17 KB
/
Copy path47ptr_to_object.cpp
File metadata and controls
53 lines (44 loc) · 1.17 KB
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
#include <iostream>
using namespace std;
class Complex
{
int real, imaginary;
public:
getData()
{
cout << "z = " << real << " + " << imaginary << "i" << endl;
}
setData(int a, int b)
{
real = a;
imaginary = b;
}
};
int main()
{
Complex c1;
Complex *p1 = &c1;
// Basic way to access class members with object
c1.setData(1, 4);
c1.getData();
// Accessing class members with pointer to the class object
(*p1).setData(2, 5);
(*p1).getData();
// Another syntax for pointer to the class object to access class members using arrow operator '->'
p1->setData(3, 6);
p1->getData();
// Using new operator for creating class pointer / object pointer
Complex *p2 = new Complex;
p2->setData(4, 7); // both syntax
(*p2).getData(); // have same function
// Creating pointer array using new operator
Complex *p3 = new Complex[3];
p3->setData(5, 8);
p3->getData();
// Using pointer arithmetic to jump to the next index address of the pointer array
(p3 + 1)->setData(6, 9);
(p3 + 1)->getData();
(*(p3 + 2)).setData(7, 10);
(*(p3 + 2)).getData();
return 0;
}