8.3 — Public vs private access specifiers

Public and private members

Consider the following struct:

In this program, we declare a DateStruct and then we directly access its members in order to initialize them. This works because all members of a struct are public members by default. Public members are members of a struct or class that can be accessed from outside of the struct or class. In this case, function main() is outside of the struct, but it can directly access members month, day, and year, because they are public.

On the other hand, consider the following almost-identical class:

If you were to compile this program, you would receive errors. This is because by default, all members of a class are private. Private members are members of a class that can only be accessed by other members of the class. Because main() is not a member of DateClass, it does not have access to date’s private members.

Access specifiers

Although class members are private by default, we can make them public by using the public keyword:

Because DateClass’s members are now public, they can be accessed directly by main().

The public keyword, along with the following colon, is called an access specifier. Access specifiers determine who has access to the members that follow the specifier. Each of the members “acquires” the access level of the previous access specifier (or, if none is provided, the default access specifier).

C++ provides 3 different access specifier keywords: public, private, and protected. Public and private are used to make the members that follow them public members or private members respectively. The third access specifier, protected, works much like private does. We will discuss the difference between the private and protected access specifier when we cover inheritance.

Mixing access specifiers

A class can (and almost always does) use multiple access specifiers to set the access levels of each of its members. There is no limit to the number of access specifiers you can use in a class.

In general, member variables are usually made private, and member functions are usually made public. We’ll take a closer look at why in the next lesson.


Make member variables private, and member functions public, unless you have a good reason not to.

Let’s take a look at an example of a class that uses both private and public access:

This program prints:


Note that although we can’t access date’s members variables m_month, m_day, and m_year directly from main (because they are private), we are able to access them indirectly through public member functions setDate() and print()!

The group of public members of a class are often referred to as a public interface. Because only public members can be accessed from outside of the class, the public interface defines how programs using the class will interact with the class. Note that main() is restricted to setting the date and printing the date. The class protects the member variables from being accessed or edited directly.

Some programmers prefer to list private members first, because the public members typically use the private ones, so it makes sense to define the private ones first. However, a good counterargument is that users of the class don’t care about the private members, so the public ones should come first. Either way is fine.

Access controls work on a per-class basis

Consider the following program:

One nuance of C++ that is often missed or misunderstood is that access control works on a per-class basis, not a per-object basis. This means that when a function has access to the private members of a class, it can access the private members of any object of that class type that it can see.

In the above example, copyFrom() is a member of DateClass, which gives it access to the private members of DateClass. This means copyFrom() can not only directly access the private members of the implicit object it is operating on (copy), it also means it has direct access to the private members of DateClass parameter d! If parameter d were some other type, this would not be the case.

This can be particularly useful when we need to copy members from one object of a class to another object of the same class. We’ll also see this topic show up again when we talk about overloading operator<< to print members of a class in the next chapter.

Structs vs classes revisited

Now that we’ve talked about access specifiers, we can talk about the actual differences between a class and a struct in C++. A class defaults its members to private. A struct defaults its members to public.

That’s it!

(Okay, to be pedantic, there’s one more minor difference -- structs inherit from other classes publicly and classes inherit privately. We’ll cover what this means in a future chapter, but this particular point is practically irrelevant since you should never rely on the defaults anyway).

Quiz time

Question #1

a) What is a public member?

Show Solution

b) What is a private member?

Show Solution

c) What is an access specifier?

Show Solution

d) How many access specifiers are there, and what are they?

Show Solution

Question #2

a) Write a simple class named Point3d. The class should contain:
* Three private member variables of type int named m_x, m_y, and m_z;
* A public member function named setValues() that allows you to set values for m_x, m_y, and m_z.
* A public member function named print() that prints the Point in the following format: <m_x, m_y, m_z>

Make sure the following program executes correctly:

This should print:

<1, 2, 3>

Show Solution

b) Add a function named isEqual() to your Point3d class. The following code should run correctly:

Show Solution

Question #3

Now let’s try something a little more complex. Let’s write a class that implements a simple stack from scratch. Review lesson 7.9 -- The stack and the heap if you need a refresher on what a stack is.

The class should be named Stack, and should contain:
* A private fixed array of integers of length 10.
* A private integer to keep track of the size of the stack.
* A public member function named reset() that sets the size to 0.
* A public member function named push() that pushes a value on the stack. push() should return false if the array is already full, and true otherwise.
* A public member function named pop() that pops a value off the stack and returns it. If there are no values on the stack, the code should exit via an assert.
* A public member function named print() that prints all the values in the stack.

Make sure the following program executes correctly:

This should print:

( )
( 5 3 8 )
( 5 3 )
( )

Show Solution

8.4 -- Access functions and encapsulation
8.2 -- Classes and class members

249 comments to 8.3 — Public vs private access specifiers

  • Nurlan

    Hello Alex,
    I hope, you are doing well! I have question regarding to quize No# 3.

    As we know return statement should be returned to the main in case there are some rules are followed as below:
    As example function - fun() is taken. Below function calls are shown.

      int res=fun(); // assuming return type is int;
       return fun();      //if it is recursive function

    Of course these are cases that often faced in our C, C++ programs.

    But,in your case you have returned the value true or false to the main(). How function call accept without following above shown rules. For example: stack.push()=true (in main).
    May we have to write according to above rules as : bool set=stack.push(); instead stack.push();

    It is kind of amazing for me that why the compiler accept them or it is a rule of object oriented program.Please Could you clarify these with example?It is new concept for me here.

    > A public member function named push() that pushes a value on the stack. push() should return false if the array is already full, and true otherwise.

    If it is acceptable in OOPs to return to the main() as in NO# 1 question.
    I didn't get the above task.
    What is the point of returning true or false of type bool. What is the use of them?

    I wrote the program below without returning the value(true,false). Is this correct. What do you think?
    class Stack{
        int size=10;
        int arr[10];
        int top;
            void reset(){
                for(int i=0;i<10;++i)
            void push(int element)
                std::cout<<"the stack is fulln";
            void pop()
                assert(top!=-1 && "Stack is emptyn");
            void print()
                std::cout<<"( ";
                for(int i=0;i<=top;++i){
                    std::cout<<arr[i]<<"  ";

    int main()
        Stack stack;






        return 0;

    • Alex

      A return value can represent whatever the function wants. It can be an value, a code representing success or failure, or anything else. When we return a bool, we're generally using that bool to represent success or failure.

      It's not wrong to return void if your function doesn't need to return anything. In the case of push(), the function doesn't need to return anything back to the caller, so using void is fine. In the case of pop(), you could return the value you just popped off the stack, or nothing (your choice). So void could be fine here too. But if these operations can fail, then it's better to return a bool instead of void so that if they do fail, the caller has some way of being notified of that failure. Otherwise, the function wouldn't have any way to signal that something had gone wrong (unless you use exceptions).

  • Camilla

    I wonder if you could help me, I'm trying to find out the software process behind using a tool in Rhino (a 3D CAD software, written in C++) I know that is uses classes and objects and sometimes wrapper classes but I dont understand the sequence triggered by a user selecting a tool in the user interface, and then using it on a model(stored data). Is there any way you might be able to shed light on this


  • J

    It is funny how the same concept can appear entirely different to two different people.  
    I think of "stacks" as literally being stacks: a pile of boxes.  When you put something in the 0th slot, all the other somethings get out of their boxes and move up one address.  When you perform an operation which takes two arguments, you use the 0th and 1st elements, and everything in the pile moves down two slots.  
    So you end up with something like:

    The output looks like this:
    (  )
    ( 8 3 5  )
    ( 3 5  )
    (  )
    ...because the elements are being pushed on, and popped off, from the left.  

    It is computationally expensive, but I always figured that systems that use stacks have some crazy kind of architecture that naturally support them.    
    My very first programming experience was in the early 1980's on an HP calculator that was entirely stack based.  It is still my natural way to think about many problems.  
    Thanks for the nice lessons and exercises.  I have been have been editing in notepad++, and compiling right from the command line with MinGW, and I have not had a single problem with any of your sample code.

    • Alex

      It's much easier to add a new box to the top of the pile than add a new box to the bottom and move content of the boxes up one box accordingly! This holds true in both C++ and real life. :)

  • Gleb

    I tried to run this program and got such errors:

    "'instantStack' was not declared in this scope", which appears wherever instantStack is used;

    invalid use of non-static data member 'Stack::fixedLength' for line with

    Can you explain what's wrong with this code and how to put it right?
    I work in Eclipse IDE, if it matters.

    • Alex

      The compiler is complaining about this line:

      My guess is that your compiler isn't C++11 compatible. So you either need to upgrade/switch to a compiler that is, enable C++11 compatibility with yours (assuming that's an option), or rewrite your code to use only non-C++11 code.

      • Gleb

        I have MinGW with support of C++11. Well, I have found solution of this problem. It was just enough to change that line to

  • josep

  • Prado

    Alex,thanks for helping so much programmers with this!

  • Matt

    In your stack quiz solution, you included header file <assert> rather than <cassert>.

  • Sivasankar

    A small typo error in line 16 in solution of problem 3 in Quiz section. I think it should be m_array instead of m_next to set array elements to '0'

  • Robby

    shouldn't this be:

    so that pop() returns the value it has just popped?

    • Alex

      Nope. In the provided solution, m_length always contains the index of the next FREE element on the stack (not the last valid element). So to return the last valid element, we need to first decrement m_length and then return the value.

      • Matthew senko

        hey can you explain this more? pop() is the only part i dont 100% understand. I see that it is taking a int off the 'stack' but how is it doing it?

        • Alex

          Since this seems to be generating a lot of questions, I've updated the example in a few ways:
          1) I've changed the name of m_length to m_next, which makes a lot more sense since it's holding the index of the next free element, not the length of the array. Bad variable naming on my part!
          2) I added a bunch of annotative comments to help people understand what's happening.

          Have a look over the solution and let me know if that helps.

  • Mauricio Mirabetti

    Alex, I tried to do something less magic numbers oriented related to length, with the following:

    , and using m_capacity throughout the code.
    At compile time, got: "a nonstatic member reference must be relative to a specific object". The only solution was to use "static constexpr" instead of const.
    Why's that again? I'm sorry if this was covered, couldn't find the answer on previous chapters.
    Thanks a lot.

    • Alex

      m_capacity isn't actually initialized until the object of the class is instantiated, which makes m_capacity a runtime constant, whereas arrays require a compile-time const.

      What's interesting is that you CAN use an enumerator (replace your const int m_capacity with "enum X { m_capacity = 10 };" and it will work), since enumerator values are defined at compile time.

      • Mauricio Mirabetti

        I understand! Really interesting. Will keep this concept in mind. Thanks!

      • Po-Shan

        Hi, Alex

        In 4.3 (Static duration variables), you didn't mention that static could set a compile-time constant. Maybe you can add it.
        And in 2.9 (Const, constexpr, and symbolic constants), you mentioned the compile-time constant keyword, constexpr. I use this but still get error. I think I'm using C++11 or higher, 'cause I can use uniform initialization.

        • Alex

          The use of static here is irrelevant in the context of runtime vs compile-time constants -- static is used here to ensure that each instance of the Stack doesn't get a separate s_maxStackLength member (to save memory)

          I've been able to compile this program on a variety of different compilers with no difficulty. What compiler are you using?

          • Po-Shan

            It seems it's a little bit of confusing now. Let me try to clarify again.
            1. I succeed to use "static const int" but fail to use "constexpr int". I try constexpr because you mentioned arrays require a compile-time constant.
            2. If static is used to save memory, then I think we can logically remove static here, and we just use more memory. However the compile error will happen after the static is removed.
            3. I use atom with gpp-compiler v3.0.7 and my gcc is of v6.3.0.

            • Alex

              Can you share the code you're trying to compile, and the specific error message you're getting?

              • Po-Shan

                It is my code.
                If I change this line to "constexpr int", the error message is
                If I change this line to "const int", the error message is

                • Hi Tommy!

                  Error 1: constexpr isn't a type. It's a modified (like const or static). You used it like a type.

                  Lesson 2.9

                  Error 2: You're trying to access a member variable without an associated object.
                  Lesson 8.11

                  • Po-Shan

                    Error 1: Sorry, there was a typo. The "constexpr int" doesn't work for me and I've updated the compile-error message.

                    Error 2: Why can't we just set a normal member variable to initialize the array?

                    • Error 1: constexpr members have to be static. There's not really more I can say about that. But having it non-const doesn't make sense, because it'd have the same value across all instances anyway.

                      Error 2: @std::array is a template function (Covered later). Whatever is inside the angle quotes (<>) has to be a compile time constant. Since @m_maxLength doesn't exist unless you instantiate an object of that class, it's value could still be changed during construction. Declaring @m_maxLength static const makes it a compile time constant, because then there's no (harmless) way of modifying it.

  • Kattencrack Kledge

    About the reset() function in the last quiz question:

    Is it okay/good practice to do it this way:

    I wanna be really sure that it's ok to do that. Sorry for the bombarding questions.

  • Rob G.

    Dear Alex,

    This was a bear of an assignment to say the least. After doing it I was so glad we have stack, vector containers. I couldn't help feeling that the solution was a "DIY" stack build. I see that every pop/push call is constructed in a "raw" manner in a class that is user made. There are no container members to use except what the user programs as a member functions in the class. What we see in the stack we are allowed to see is created by moving the length up and down in a sort of roving window. Just a suggestion maybe you could add a hint in the exercise to not use available containers. That would have saved me considerable time trying to determine which container (in this case none or made from "scratch") to use. Also, if you use a for each loop in pop/push/reset u break this delimiter based stack by seeing the whole array all the time with numbers to 10. For e.g. the stack is the same all the time if u print it out with a for-each loop. Anyway I learned an awful lot but was a little disappointed I actually had to consult the answer.

    Can u plz tell me why I am getting a one-off on line 32?

    • Alex

      I've updated the quiz instructions to note that you'll be doing this from scratch.

      Your code is slightly wrong because your push does a pre-increment on length instead of a post-increment. This means your stack effectively starts at array index 1 instead of 0, which is why you're having to offset your array indices in function print().

  • Vijin

    Thank you Alex! I really need to brush up on the basics again before going any further.

  • Vijin

    At this point,

    does it only add a value into the array, or does m_length get incremented too? I can't see an association of m_length to the actual length of the array.

  • Nyap

    so are enumerations in an enum class private/protected

  • Jim

    In this exercise.

    Moot point, why make a class Point3d private, when your using all three of its members variables as input in the two public functions.

  • T

    Aha!! I did it all with std::array only to find out that it would not work!

  • Shiva

    Hi Alex, I have a couple of questions:

    * Use of private: in class declarations given in the quiz solutions is superfluous. Is it just for demonstration or is that a programming practice?
    * This might sound a bit dumb: is it preferable not to prefix public member functions with m_ ?

    In Quiz #3, you didn't specify what pop() should return if there are values on the stack.

    BTW nice lesson, I liked the quiz questions very much. Brilliant! :)

    • Shiva

      Sorry, I meant to ask: is it preferable not to prefix public members with m_ ? If it is only for private members, then what about private member functions (if any)?

      • Alex

        By common convention:
        All public and private member variables should be prefixed by m_ (unless they are static, in which case they should use s_).
        All public and private member functions should not use a prefix.

    • Alex

      1) Yes, explicitly declaring private can be superfluous. However, I always add it, both because it makes my intent explicit, and that way, if I later decide to add something public above it, I don't risk accidentally making all of the members that were implicitly private now public. Since there's no performance penalty for doing so, I like being a little defensive here.
      2) Usually only member variables are prefixed with m_. Member functions typically aren't, regardless of whether they're public or private.
      3) I've updated the instructions to be explicit about what pop() should return. Thanks for pointing that out.

  • P

    shouldn't it be

    if we want to return the popped valued?

    • Alex

      No. As implemented, length holds the index of the next free element (which is one element past the top of the stack). Therefore, we need to first decrement (to get to a valid element) and then evaluate.

  • John Mounir

    this is extremely helpful tutorial, Thank you so much.

  • sitaram chhimpa

    Can anyone suggest while below code is not working for 3rd question is giving me initial len as -2 while initilized by 0 in reset function.

    • Alex

      you're not initializing your member variable len, you're initializing a new local variable with the same name instead.

      Remove the int prefix so it knows you mean member variable len instead of a new local variable.

  • BlueTooth4269

    Isn't static technically an access specifier if you're defining your class in another cpp file?

  • Batyr

    Hey, Alex! Could you please explain me why if m_length is equal to 10 return false? why not 9?

    for example, if length is already 9, it will continue to the next statement, and how it is going to assign [m_length++] => [10] to the array? if subscripts are from 0 to 9? Or maybe bcz of increment operator order?


    • Alex

      We used the postfix increment operator here, not the prefix increment operator. So m_length isn't incremented until after it's evaluated.

      So when m_length is 9 and the function is called:

      is essentially the same as:

      You can see that m_length is evaluated to be 9 first, then it's incremented to 10.

      And if m_length is 10, that's an invalid index for our array, so we ignore the push request so we don't walk off the end of the array.

  • Colleen

    I'm very glad you include sample code.

    What IDE are you using to compile and run your code? I have NetBeans installed on my computer, and I tried to run the "employee" example program, but I got compilation errors ("'cout' is not a member of 'std'"). Do you recommend NetBeans--or do you have an IDE you'd recommend?


    • Alex

      NetBeans is okay, but it sounds like your compiler is out of date. NetBeans has support for multiple compilers -- maybe you can change to a more modern compiler version.

  • I have few questions Alex...

    In the previous lesson you said that structs can't include functions. In this lesson I have a confusion with this line:

    "One of the primary differences between classes and structs is that classes can explicitly use access specifiers to restrict who can access members of a class"

    The following program works fine:

    I can define a function inside a struct. I can strict members using public and private. Till this point, I only can see a single difference between struct and classes that class members are by default private and struct members are public. Are we missing something???

    The wikipedia also has an article containing an example where struct is used and shown that its members are restricted.

    • Alex

      Yes, the previous statement was misleading (and has been corrected) -- the intent was to say that data-only structs were non-object-oriented, not all structs. In C++, structs are like classes where all the members are public by default.

  • Nate

    I did not struggle with c++ at all until I hit classes.  I have been stuck on them for a week now and feel that I am making very little progress.  Is that normal for most people?  Thankyou

    • Alex

      Yes, making the shift from normal functions to objects can be a little hard to wrap your brain around. But once you "get it", you won't want to go back.

      What specifically are you stuck on?

  • Marvin

    I'm missing the quizzes to apply my just received knowledge like in former chapters!

  • Joseph

    Does C++ only accept class members declared with the public:, private: and protected: access specifiers?
    Would writing them like this also work?

    • C++ newbie

      I just tried compiling that and it didn't work.  It said that it needed the colon after public.  I know you can declare things like this in other languages, though (like Java)

  • Spock

    Another great tutorial. You write really well man.

  • vinoth

    by default class is public or private in c++

Leave a Comment

Put all code inside code tags: [code]your code here[/code]