Public Access Modifier
Published Jan 28, 2025Updated Jan 28, 2025
Contribute to Docs
In C++, access modifiers control how and where class members (variables and methods) can be accessed. The public
keyword makes the associated members accessible from anywhere in the program. This means any code that has access to an instance (object) of the class can read, write, or invoke these members directly.
Syntax
class ClassName {
public:
// Public members
};
Example
The following example demonstrates how to use the public
keyword in a class definition:
#include <iostream>class MyClass {public:// Public member variableint publicVar;void sayHello() {// Public member functionstd::cout << "Hello from MyClass!\n";}};int main() {MyClass obj;// Directly access the public variableobj.publicVar = 42;std::cout << "obj.publicVar = " << obj.publicVar << std::endl;// Call the public methodobj.sayHello();return 0;}
The above code will result in the following output:
obj.publicVar = 42Hello from MyClass!
Codebyte Example
Below is a runnable snippet showcasing public
access in a simple C++ class:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours