1 Namespace#
Namespaces can serve as additional information to distinguish functions, classes, variables, etc., with the same name in different libraries; essentially, a namespace defines a scope.
1.1 Defining a Namespace#
Use the keyword namespace, followed by the name of the namespace.
namespace ns_name
{
//code
}
To call a function or variable within that namespace, use:
ns_name::code;
2 Class#
Defining a class requires the keyword class, followed by the name of the class, with the body of the class enclosed in a pair of curly braces, containing the class's member variables and member functions.
2.1 Accessing Data Members#
Use .
to access variables within the class.
2.2 Class Access Modifiers#
Data encapsulation is one of the important features of object-oriented programming, preventing functions from directly accessing the internal members of a class. Access restrictions for class members are specified by marking various areas within the class body as public, private, protected
. The default access modifier for members and classes is private
.
2.2.1 public#
Public member variables can be set and retrieved without using any member functions in the program.
2.2.2 private#
Private members are not accessible from outside the class; only the class and friend functions can access private members. By default, all members of a class are private. In practice, data is generally defined in the private area, while related functions are defined in the public area, allowing access to data from outside the class.
2.2.3 protected#
Protected members are similar to private members, but protected members are accessible in derived subclasses.
2.2.4 Characteristics in Inheritance#
- private members can only be accessed by members of the class and friends, and cannot be accessed by derived classes.
- protected members can be accessed by derived classes.