VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-create-class-with-private-and-public-members-in-cpp/

⇱ How to Create a Class with Private and Public Members in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Create a Class with Private and Public Members in C++?

Last Updated : 23 Jul, 2025

In C++, the classes are blueprints for creating objects with specific properties and methods that provide a feature of access specifiers to the user through which they can control the access of the data members present in a class. In this article, we will learn how to create a class with private and public members in C++.

Define Private and Public Members in a Class

In C++, class members can be declared as privatepublic, or protected. By default, all members of a class are private if no access specifier is specified.

  • Private: Members declared as private can only be accessed within the class.
  • Public: Members declared as public can be accessed from anywhere in the program.

Syntax to Define Private and Public Members in a Class

class ClassName {
private: // Private members
dataType member1;
dataType member2;
// ...

public: // Public members
dataType member3;
dataType member4;
// ...
};

Here,

  • ClassName is the name of the class.
  • private: and public: are access specifiers.
  • dataType represents the type of the data member.
  • member1member2member3, and member4 are the names of the data members.

C++ Program to Create a Class with Private and Public Members

The following example illustrates how we can create a class with private and public members in C++.


Output
Public member is : 100
This is a public method
This is a private method

Time Complexity: O(1)
Auxiliary Space: O(1)



Comment