C2248
Visual C++ Programming Language
Severity: MinorWhat Does This Error Mean?
C2248 means code outside a class (or outside a derived class, for protected members) is trying to read or write a member that was declared private or protected. The message reads: C2248: 'member': cannot access private member declared in class 'type'. The fix is to use a public getter or setter, make the member public if appropriate, or declare the accessing code as a friend.
Affected Models
- Visual Studio 2015–2022
- MSVC v14.x / v17.x
Common Causes
- Accessing a private data member directly from outside the class
- Calling a private constructor or factory method from code that is not a friend
- A derived class trying to access a private (not protected) base class member
- Copy or move assignment attempting to access private members of the source object
How to Fix It
-
Add a public getter or setter method to the class. This is the standard C++ way to expose controlled access to private data.
Getters return the value; setters validate and set it. This keeps the class in control of its own data — callers cannot bypass validation.
-
If the member genuinely needs to be accessible from a specific external function or class, declare it as a friend. Add friend class OtherClass; or friend void someFunction(); inside your class definition.
Friend declarations grant full access to private and protected members. Use sparingly — they tightly couple the two types.
-
If a derived class needs the member, change its access specifier from private to protected. Protected members are accessible in derived classes but still hidden from unrelated code.
private means only this class. protected means this class and derived classes. public means everyone. Choose the most restrictive level that satisfies your design.
Frequently Asked Questions
Can I suppress C2248 with a pragma?
No — C2248 is a hard error, not a warning. It reflects a real access-control violation that the language forbids. The only fix is to change the access level, add a public accessor, or grant friendship.