Public Access Modifier

MamtaWardhani's avatar
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 variable
int publicVar;
void sayHello() {
// Public member function
std::cout << "Hello from MyClass!\n";
}
};
int main() {
MyClass obj;
// Directly access the public variable
obj.publicVar = 42;
std::cout << "obj.publicVar = " << obj.publicVar << std::endl;
// Call the public method
obj.sayHello();
return 0;
}

The above code will result in the following output:

obj.publicVar = 42
Hello from MyClass!

Codebyte Example

Below is a runnable snippet showcasing public access in a simple C++ class:

Code
Output
Loading...

All contributors

Contribute to Docs

Learn C++ on Codecademy