Chapter6_Class_and_Objects_part1
Chapter6_Class_and_Objects_part1
© HĐC 2024.1
Content
6.1. Definitions
6.2. From structure to classs
6.3. Member variables
6.4. Member functions
6.5. Access control
Attributes
State
Data
Relationship
Behaviour
Operation
Response
Identity
Semantic/responsibility
Direct access to the data without strictly control would results in unsafe
operation
Time t1 = {1, 61, -3};// ??!
Time t2;// Uncertain values
int h = t2.hour;// ??!
int m = 50;
t2.min = m + 15;// ??!
There is no difference between “internal details” and “external interface”, a
trivial modification requires users to change the source code
E.g.: the name of one member variable in Time structure has been changed
struct Time {
int h, m, s;
};
The old code cannot be used:
Time t;
t.hour= 5;
Usually, class and member variables are declared in a header file (*.h).
E.g. in “mytime.h”:
class Time {
int hour,min,sec;
public:
void addHour(int h);
void addMin(int m);
void addSec(int s);
...
};
Functions are often defined in source file (*.cpp):
#include “mytime.h”
...
void Time::addHour(int h) {
hour += h;
}
void main() {
Time t1,t2; // automatically call the constructor Time() for t1 and t2
t1.addHour(5); // same as addHour(&t1,5);
t2 = t1; // OK
t2.addHour(5); // same as addHour(&t2,5);
...
}