Classes
Classes
This domain tests class definition, access control, member functions and objects. A class binds data members and member functions. private members are accessible only inside the class; public members form the interface; protected is used with inheritance. By default, class members are private; in a struct they are public.
Rules
- Define with
class Name { ... };and note the semicolon. - Member functions can be defined inside the class (inline) or outside using
Name::function. - Create objects with
Name obj;and access public members withobj.member. - Keep data private and expose operations; this is encapsulation and data hiding.
Worked example
class Rectangle { private: int l, w; public: void set(int a, int b) { l=a; w=b; } int area() { return l*w; } };
Rectangle r; r.set(4,3); cout << r.area(); prints 12. r.l = 5; would be illegal in main because l is private; the public set function is the controlled route. The object r has its own l and w, separate from any other Rectangle object.
Traps
Forgetting the semicolon after the class definition. Trying to access private data directly from main. Confusing the class name with an object name. A member function defined outside needs the scope-resolution operator. Class definitions do not allocate memory; objects do.