Class Design in C++

Defining a Class

To define a class, we use the 'class' keyword, followed by the name of the class and a pair of curly braces that enclose the class's data members and member functions. For example:

class MyClass {
  int myVar;          // data member
  void myFunction();  // member function
};
Note that the class definition ends with a semicolon. After defining a class, we can create objects of that class type by declaring variables of the class type:
MyClass obj;

Access Modifiers

Access modifiers determine the visibility of class members (variables and functions). There are three access modifiers in C++:

  • public: Members are accessible from any part of the program.
  • private: Members are accessible only within the class.
  • protected: Members are accessible within the class and its derived classes.
By default, all members of a class are private. To specify the access level for members, use the corresponding access modifier followed by a colon:
class MyClass {
public:
  int myVar;
  void myFunction();

private:
  int myPrivateVar;
};
In this example, 'myVar' and 'myFunction()' are public, while 'myPrivateVar' is private.