Each property of the object is represented by one value (stored in a variable)
These variables collectively represent complete information on the entity
Conceptually: "Student = (name, address, phone_number, major)" |
|
struct StructureName { type1 element1; type2 element2; type3 element3; ... }; |
Example:
struct myStruct { int i; float f; }; |
struct myStruct x, A[3]; |
|
class ClassName { [private:] [public:] [protected:] type1 var1; type2 var2; type3 var3; ... }; |
Example:
class myClass { public: int a; // public float b; // public private: int a; // private float b; // private protected: int a; // protected float b; // protected } ; // ***** NOTE: ends in a semi-colon !!! |
|
ClassName variableName; |
Example:
myClass x; // x is a myClass variable myClass a[10]; // array of 10 variables myClass *p; // p contains an address of myClass variable |
The object itself (representation of the real entity) is created using the new operator
class myClass { int x; float y; }; myClass a; myClass b[4]; |
will create the following:
|
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 |