C++ Notes: Classes - Visibility - public and private
Public and Private parts
All members (fields and methods) of a class are private by default
(no code outside the class can reference them), whereas
fields of a struct are public, meaning that anyone
can use them. For example,
struct Product {
char mfg_id[4]; // 4 char code for the manufacturer.
char prod_id[8]; // 8-char code for the product
int price; // price of the product in dollars.
int qty_on_hand; // quantity on hand in inventory
};
could be rewritten as a class like this
class Product {
public:
char mfg_id[4]; // 4 char code for the manufacturer.
char prod_id[8]; // 8-char code for the product
int price; // price of the product in dollars.
int qty_on_hand; // quantity on hand in inventory
};
The public
and private
keywords may be written
before any declarations, but it is common to group all public
members, then all private members. For example,
class Point {
public:
int getX();
int getY();
int setX();
int setY();
private:
int x;
int y;
};