These variables collectively represent (more) complete information on the same entity and are group together for convenience
Conceptually: "Student = (name, address, phone_number, major)" |
struct StructureName { type1 element1; type2 element2; type3 element3; ... }; |
Example: struct myStruct { int i; float f; }; |
struct StructureName variableName; |
struct myStruct x, A[3]; |
class ClassName { [private:|public:|protected:] type1 element1; type2 element2; type3 element3; ... }; |
Example: class myClass { public: int i; float f; }; |
After defining the class structure, you can define variables of this class as follows:
ClassName variableName; NOTE: no keyword "class" !!! |
A class is a complete type that behave exactly like built-in data types:
Functions and Operations defined inside a class are called member functions/operations |
There are 3 levels of security:
For now, I will ALWAYS use public: - the difference will be explained later... |
struct myStruct x; // Definition of the struct variable x |
myClass x; // Definition of the class variable x |
struct myStruct class myClass { { public: int i, j, k; int i, j, k; float x, y, z; int x, y, z; }; }; struct myStruct x; myClass x; | |
x.i |
The component (integer) variable "i" in "x" |
x.x |
The component (float) variable "x" in "x" |
&(x.i) |
Address of the component variable "i" in "x" |
x |
The entire object "x" (all components) |
&x |
The address of "x".
It is also equal to the address of the first component (variable i) in "x" |
void Print1(struct myStruct h) { cout << "Structure values = (" << h.i << ", " << h.f << ")\n"; h.i = h.i + 1000; h.f = h.f + 1000; } |
void Print2(myClass h) { cout << "Structure values = (" << h.i << ", " << h.f << ")\n"; h.i = h.i + 1000; h.f = h.f + 1000; } |
void Print1(struct myStruct & h) { cout << "Structure values = (" << h.i << ", " << h.f << ")\n"; h.i = h.i + 1000; h.f = h.f + 1000; } |
void Print2(myClass & h) { cout << "Structure values = (" << h.i << ", " << h.f << ")\n"; h.i = h.i + 1000; h.f = h.f + 1000; } |
Class variable definition:
class myClass { public: int i; float f; }; myClass x; // x is a myClass variable myclass *p; // p is a reference variable // (reference a myClass variable p = &x; // Now p points to x (*p).i = 4; // equivalent to x.i (*p).f = 3.14; // equivalent to x.f |
(* reference_var).MEMBER |
is a commonly used expression, C/C++ has a short hand for this expression:
reference_var->MEMBER |
p->i = 4; // equivalent to (*p).i p->f = 3.14; // equivalent to (*p).f |