forked from wadehuber/codeexamples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstructvsclass.cpp
More file actions
68 lines (55 loc) · 1.72 KB
/
Copy pathstructvsclass.cpp
File metadata and controls
68 lines (55 loc) · 1.72 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include<iostream>
#include<string>
#include<string.h>
#include<stdio.h>
using namespace std;
// C-style structure
struct myStruct {
int a;
char c[16];
myStruct(int x, const string & y) : a(x) {
cout << "myStruct constructor" << endl;
strncpy(c, y.c_str(), y.length() + 1);
}
void dump(unsigned int x=16) {
cout << endl << "myStruct: a=" << a << " c=" << c << endl;
char * ptr = (char *) this;
for(unsigned int ii=0;ii<x;ii++) {
printf("%3u: %5c %5x %5d\n", ii, *(ptr+ii), *(ptr+ii), *(ptr+ii));
}
}
};
// C++ class
class myClass {
int a;
string c;
public:
myClass(int x, const string & y) : a(x), c(y) {
cout << "myClass constructor" << endl;
}
void dump(unsigned int x=16) {
cout << endl << "myClass: a=" << a << " c=" << c << endl;
char * ptr = (char *) this;
for(unsigned int ii=0;ii<x;ii++) {
printf("%3u: %5c %5x %5d\n", ii, *(ptr+ii), *(ptr+ii), *(ptr+ii));
}
}
};
int main() {
cout << "Declaring variabls:" << endl;
struct myStruct str = {7, "Hello"};
myClass cls(15, "World");
cout << endl;
cout << "Sizes: " << endl;
cout << "myStruct size=" << sizeof(myStruct) << endl;
cout << " myClass size=" << sizeof(myClass) << endl;
cout << endl;
cout << "Accessing members:" << endl;
cout << " myStruct.a = %d" << str.a << endl; // struct members are public by default
//cout << " myClass.a = %d" << cls.a << endl; // class members are private by default
cout << endl;
cout << "Calling dump():" << endl;
str.dump(sizeof(str));
cls.dump(sizeof(cls));
return 0;
}