Search

Admin

8.3 — Public vs private access specifiers

Access specifiers

Consider the following struct:

In this program, we declare a DateStruct and then we directly access it’s members in order to initialize them. This works because all members of a struct are public members. Public members are members of a struct or class that can be accessed by any function in the program.

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

If you were to compile this program, you would receive an error. 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 functions within the class. Because main() is not a member of the Date class, it does not have access to Date’s private members.

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

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

C++ provides 3 different access specifier keywords: public, private, and protected. We will discuss the protected access specifier when we cover inheritance.

Here is an example of a class that uses all three access specifiers:

Each of the members “acquires” the access level of the previous access specifier. It is common convention to list private members first.

Why would you want to restrict access to class members? Oftentimes you want to declare members that are for “internal class use only”. For example, when writing a string class, it is common to declare a private member named m_nLength that holds the length of the string. If m_nLength were public, anybody could change the length of the string without changing the actual string! This could cause all sorts of bizarre problems. Consequently, the m_nLength is made private so that only functions within the String class can alter m_nLength.

The group of public members of a class are often referred to as a “public interface”. Because only public members can be accessed outside of the class, the public interface defines how programs using the class will interface with the class.

So what’s the difference between a class and a struct? Very little! In C++, a class defaults its members to private. A struct defaults its members to public. That’s it!

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

22 comments to 8.3 — Public vs private access specifiers

  • vinoth

    by default class is public or private in c++

  • buck

    compiling code in first example gives me an error - (22) : error C2440: ‘return’ : cannot convert from ‘int’ to ‘DateStruct’. By adding a semi-colon (;) after closing curly brace of structure, it compiles without error. I am using MS Visual C++.

    [ Oops, yes, all structs and classes must end with a semicolon. Forgetting it will cause errors on many compilers. -Alex ]

  • Spock

    Another great tutorial. You write really well man.

  • Jon

    Hi Alex,

    I want to clarify to see if I understood your statements correctly….”For example, when writing a string class, it is common to declare a private member named m_nLength that holds the length of the string. If m_nLength were public, anybody could change the length of the string without changing the actual string!”

    Do you mean…

    Class Letter
    {
    int m_nLength = 14;
    };

    ??????????????

    Thank you.

    • Bob

      You can’t initialize a class member in the class itself. (except static const int). But yes, I think you understand. Although the class wouldn’t just have that member alone. Also remember class is spelled lower cased.

  • serenity

    “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.”
    This is incorrect - *the only* difference is that classes default to private, and structs to public. You can use private: and protected: in a struct, as well as have member functions.

    They are usually used in different ways, but that’s mostly for code clarity, not because you need it. You can create a struct with inheritance, member functions etc.

    • Pankaj

      yes you are right serenity, we can use access specifiers(public,private and protected)and your own constructor, destructor, copy constructor and assignment operator in structs as well.

    • pshetty

      yes this is true…the tutorial is great alex…but i think there are certain areas where you need to relook, for example what serenity is pointing out

  • 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)

  • Marvin

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

  • 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?

  • 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.

    https://en.wikipedia.org/wiki/Access_modifiers

    • 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.

  • "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"

    You forgot to update this line(in this lesson). structs also allow us to explicitly restrict its members using access specifiers.

  • 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?

    Thanks!

    • 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.

Leave a Comment

  

  

  

1 × four =

Put C++ code inside [code][/code] tags to use the syntax highlighter