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 |
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:
|
Because there are differences in how the data is stored, I will discuss the meaning of the various expression in some detail.
class myClass { public: int x; float y; }; |
with the following variable definitions:
myClass a; myClass b[4]; |
a.x = 12; b[1].y = 34; |
will result in:
Examples: (using the above figure)
&(a.x) returns 3404 &(a.y) returns 3408 &a returns 3404 &(b[0].x) returns 4216 &(b[0].y) returns 4220 &(b[2].x) returns 4232 &(b[0]) returns 4216 &b returns 4216 |
Example:
myClass *p; // p contains an address of myClass variable |
Example:
myClass a; myClass *p; p = &a; // p points to variable a |
(It looks similar to an object variable pointing to ab object in Java.
It is indeed the same situation, except the "object" a was not created by a new operation - rather, it was allocated through a variable definition)
Example:
myClass a; myClass *p; p = &a; // p points to variable a |
(*p).x |
is a very commonly used expression in C++
(You will see it in linked lists)
p -> x <==> (*p).x |
You must write -> without any spaces between these 2 characters !
Example program:
class myClass // How to define a "class" type { // This is NOT a variable definition public: int x; // It serves to tell C++ what "myClass" looks like float y; }; |
extern className varName; |
myClass x; // Definition of the class variable x |