Access Specifiers in C++
Access Specifiers in C++
University
Computer Science Faculty
Object Oriented
Programming (C++)
C++
Access Specifiers
Outline
Access Specifiers
Types of Access Specifiers
Access Specifiers Examples
Access Specifiers
By now, you are quite familiar with the public
keyword that appears in all of our class
examples:
Example
class MyClass { // The class
public: // Access specifier
// class members goes here
};
Note
The public keyword is an access specifier.
Access specifiers define how the members
(attributes and methods) of a class can be
accessed.
In the example above, the members are public
- which means that they can be accessed and
modified from outside the code.
However, what if we want members to be
private and hidden from the outside world?
Three Access Specifiers
public - members are accessible from outside
the class
private - members cannot be accessed (or
viewed) from outside the class
protected - members cannot be accessed
from outside the class, however, they can be
accessed in inherited classes. You will learn
more about Inheritance later.
Three Access Specifiers
In the following example, we demonstrate the
differences between public and private
members:
Example (Part 1)
Example (Part 2)
Attention!
If you try to access a private member, an error
occurs:
error: y is private
Note 1
It is possible to access private members of a
class using a public method inside the same
class.
See the next chapter (Encapsulation) on how
to do this.
Note 2
It is considered good practice to declare your
class attributes as private (as often as you
can).
This will reduce the possibility of yourself (or
others) to mess up the code.
This is also the main ingredient of the
Encapsulation concept, which you will learn
more about in the next chapter.
Note 3
By default, all members of a class are
private if you don't specify an access
specifier:
Any Questions?