C++ Data Sharing and Protection
Identifier Scope and Visibility
Scope
Scope is the valid region where an identifier is effective in the program text.
Function Prototype Scope
The scope of formal parameters during function prototype declaration is the function prototype scope.
In function prototype parameter lists, only the type matters, not the identifier, which can be omitted. For readability, it’s better to include it.
Local Scope
Simply understood as variables declared within function bodies, from the declaration point to the closing brace of the block where the declaration is located.
Variables with local scope are also called local variables.
Class Scope
A class is a collection of named members, and its member m has class scope. There are three ways to access it:
- If member m is not defined in the member function and is not masked by the function body, the function can directly access m;
- Through expressions
x.morX::m. This is the most basic method, with the latter mainly used to access static members of the class. - Through
ptr->maccess, where ptr is a pointer to an object of that class.
Namespace Scope
The purpose of namespaces is to eliminate ambiguity that may exist in different files in a project, for example: when variables in two different modules have the same name.
The syntax is as follows:
1 | namespace namespace_name{ |
Within the namespace, identifiers defined in the current space can be
used directly. If you need to use identifiers defined in other
namespaces, you need to use namespace_name::identifier. To
avoid verbosity, using statements are provided.
There are two forms of using statements:
1 | using namespace_name::identifier |
Two special types of namespaces—global namespace and anonymous namespace.
The global namespace is the default namespace, and identifiers declared outside explicitly declared namespaces are all in a global namespace.
Anonymous namespace only needs to omit the namespace name when defining, and its purpose is to prevent identifiers you define from being accessed by any other namespace.
All identifiers in the C++ standard library are declared in the std namespace, cout, cin, endl are all like this, so every program uses
using namespace std, otherwise you need to usestd::cin…
Additionally, namespaces allow nesting.
Variables with namespace scope are also called global variables.
Visibility
The content is relatively simple and straightforward, so it’s omitted.
Object Lifetime
Static Lifetime
Objects whose lifetime is the same as the program’s runtime are said to have static lifetime, and the keyword static needs to be used when declaring.
Characteristics: A copy is not created with each function call, nor does it become invalid when the function returns. Variables are shared during each call period. Assignment is performed only once, and the assignment statement at declaration is not executed multiple times.
If not initialized at declaration, it defaults to 0.
Dynamic Lifetime
Local lifetime objects are born at the declaration point and end when the block where the declaration is located finishes execution.
Class Static Members
Objects also need to share data with each other, and static members solve this problem.
For example, if there’s an Employee class, we have several Employee objects, but how do we count how many Employee objects there are? This is when static data members can be used, as this data member is shared by all objects.
Static Data Members
When a certain attribute is shared by the entire class and does not belong to any specific object, the static keyword is used to declare it as a static member. There is only one copy in the entire class, maintained and used by all objects.
Because it doesn’t belong to any object and has static lifetime, it is accessed through the class name. “class_name::identifier”.
In the class definition, only a reference declaration is made. A definition declaration must be made somewhere in the namespace scope using the class name qualifier, where initialization can also be performed.
Program example:
1 |
|
Static Member Functions
There’s actually a problem in the above program: the showcount function requires the existence of a Point object to be called, but what if I want to directly output the value of count? This is when static member functions are needed, allowing direct function calls through the class name without depending on objects.
Although static member functions can also be accessed using objects, it’s generally customary to access them through the class name. Even when accessed through an object name, the function has no relationship with the object.
Class Friends
Using the Point class as an example, what if we need a function to calculate the distance between two points?
Setting it as an ordinary function outside the class doesn’t reflect the connection between the function and points, and can’t directly use point coordinates;
Setting it as a member function inside the class doesn’t conform to the abstraction that a class represents the characteristics of a type of thing, because distance represents the relationship between points, not the characteristics of a point.
In class composition, there’s a Point and Line class, and the Line class has a function to calculate line segment length. But if we’re facing many points and frequently need to calculate distances between any two points, do we need to construct a Line class every time? This is obviously very troublesome.
Friend relationships provide a mechanism for data sharing between member functions of different classes or objects, and between class member functions and general functions.
In a class, the keyword friend is used to declare functions as friend functions and classes as friend classes. All functions of a friend class are friend functions.
Friend Functions
These are non-member functions modified with the keyword friend in a class. They can be ordinary functions or member functions of other classes. In the function body of friend functions, private and protected members of the class can be accessed through object names.
There’s practice source code on github.
Friend Classes
Similar to friend functions. If class A is a friend class of class B, then all member functions of class A are friend functions of class B and can access private and protected members of class B.
Special attention ⚠️:
- Friend relationships are not transitive. If B is a friend of A and C is a friend of B, C is not a friend of A without explicit declaration.
- Friend relationships are unidirectional. If B is a friend of A, B can access A, but A cannot access B.
- Friend relationships are not inherited. If B is a friend of A, B’s derived classes do not automatically become friends of A. A simple analogy is: if someone trusts your father, they don’t necessarily trust you.
Shared Data Protection
Constant Objects
The data value members of constant objects cannot be changed during the entire lifetime of the object. Constant objects must be initialized and cannot be updated.
Specifying initial values at definition is called initialization, and subsequent changes through assignment operations are called assignment. Don’t confuse initialization with assignment!
Class Members Modified with const
Constant Member Functions
Declaration format:
1 | type_specifier function_name(parameter_list) const; |
Note ⚠️:
- If an object is a constant object, only constant member functions can be called through that constant object, other member functions cannot be called! This is C++’s protection for constant objects and is the only external interface method for constant objects.
- Whether called through a constant object or not, during the call of a constant member function, the target object is treated as a constant object. Therefore, constant member functions cannot update the data members of the target object, nor can they call member functions of that class that are not modified with const for the target object (ensuring that constant member functions do not modify the data member values of the target object).
- The const keyword can be used to distinguish overloaded functions (functions with the same name but with or without const are different functions).
Constant Data Members
Data members declared with const are constant data members, and no function can assign values to them. Constructors can only obtain initial values through initialization lists for these data members.
Static variables and constants in class members should be defined outside the class definition, but C++ provides an exception: if a class’s static constant has integer type or enumeration type, the constant value can be directly specified in the class definition.
Constant References
If a reference is modified with const when declared, the declared reference is a constant reference, and the object referenced by the constant reference cannot be updated. When used as function parameters, it prevents accidental changes to actual parameters.
For parameters whose values cannot be changed in functions, it’s not suitable to use ordinary reference passing, as it would prevent constant objects from being passed in. Using pass-by-value or passing constant references can avoid this problem. Pass-by-value is more time-consuming, so passing constant references is better. Copy constructor parameters generally also choose constant references!
Multi-file Structure and Compilation Preprocessing Commands
Since there’s a foundation in C language, this section only lists some unfamiliar and less memorable content.
General Organization Structure of C++ Programs
A project can be divided into multiple source files:
- Class declaration files (.h files)
- Class implementation files (.cpp files)
- Class usage files (.cpp files containing main())

Standard C++ Library
The standard C++ class library is a collection of extremely flexible and extensible reusable software modules.
Standard C++ classes and components are logically divided into 6 types:
- Input/Output classes
- Container classes and abstract data types
- Storage management classes
- Algorithms
- Error handling
- Runtime environment support
Comprehensive Example—Personal Bank Account Management Program
The program source code has been uploaded to github and compiled using makefile.
Serious error: static variables were not assigned initial values externally, causing my progress to stagnate for two hours, and the initialization assignment was done in the file where the class member functions are defined.









