C++: Security and Scope, Access Specifiers and the this Pointer

Learn how to protect an object's data with access specifiers, expose it safely through getters and setters, and use the this pointer to resolve naming conflicts.

Why Protect Data?

Without any restrictions, any part of the program can reach into an object and change its data directly. This makes it easy to put an object into an invalid state, for example, setting a circle's radius to a negative number. Access specifiers let a class control exactly who is allowed to read or modify its members.

Encapsulation

Encapsulation is the practice of keeping an object's internal data private and providing a controlled public interface for reading and changing it.

  • Private data cannot be accidentally modified by unrelated code
  • Validation logic lives in one place: the setter function
  • The internal representation can change without breaking callers, as long as the public interface stays the same
  • Think of it as a vending machine: you interact with the buttons, not the internal wiring

public: Open to Everyone

Members declared under public: are accessible from anywhere the object is visible, inside the class, in derived classes, and in code outside the class entirely. Public members form the interface that callers interact with.

public

Declare member functions as public so callers can use the object. Keep data members private and expose them only through functions.

  • Accessible from: inside the class, derived classes, and all external code
  • Constructors are almost always public so objects can be created by callers
  • Member functions intended for external use go here
  • Avoid placing raw data members in the public section unless the type is a simple data holder

public Member

C++

radius is public, so main() can read and write it directly.

private: Restricted to the Class

Members declared under private: are accessible only from inside the class itself. No external code, not even a derived class, can read or write them directly. This is the default for class members when no specifier is given.

private

Declare data members as private. Then write public getter and setter functions to give controlled access to those values.

  • Accessible from: inside the class only
  • Attempting to access a private member from outside the class is a compile error
  • Data members are typically private to prevent invalid state
  • Setters can validate input before assigning: reject a negative radius before it is stored

private with Getter and Setter

C++

radius is hidden. The setter rejects negative values; direct access from outside is a compile error.

protected: Shared with Derived Classes

Members declared under protected: behave like private members to all outside code, but derived (child) classes can access them directly. This is a preparation for inheritance: you protect data from random outside code while still allowing subclasses to build on it.

protected

Use protected when you know a member will be needed by subclasses but should stay hidden from all other code.

  • Accessible from: inside the class and any class that inherits from it
  • Not accessible from unrelated external code
  • Common in base classes that are designed to be inherited
  • If you are not designing for inheritance, prefer private over protected
SpecifierInside the classDerived classOutside code
publicYesYesYes
protectedYesYesNo
privateYesNoNo

Getters and Setters

A getter is a public function that reads and returns a private member. A setter is a public function that validates and then writes to a private member. Together they form the controlled public interface that hides the raw data but still makes it usable.

Getter and Setter Pattern

Getters read private state; setters write it with optional validation. This is the standard way to expose private data without giving direct access.

  • Getter naming convention: getX() returns the value of member x
  • Setter naming convention: setX(value) assigns to member x after validation
  • A getter that should never modify the object should be marked const
  • You can provide a getter without a setter to make a member effectively read-only from outside

Circle with Getter and Setter

C++

Private radius is only reachable through setRadius and getRadius. Invalid values are blocked at the setter.

The this Pointer

Inside any non-static member function, this is a pointer that holds the address of the object the function was called on. C++ passes it automatically, you never see it in the parameter list. Its most common use is resolving a name conflict when a parameter has the same name as a member variable.

this pointer

this always points to the current object. Writing this->member makes it explicit that you mean the object's member, not a local variable of the same name.

  • Type: a pointer to the current class, e.g. Circle* inside Circle methods
  • Use this->radius when a parameter is also named radius to disambiguate
  • Without this->, the local parameter shadows the member variable
  • Can also return *this to enable method chaining

this Pointer in a Setter

C++

this->radius refers to the member; plain radius refers to the parameter. Without this->, the assignment would do nothing useful.

Returning this for Method Chaining

Returning *this from a setter gives back a reference to the current object. This allows multiple setter calls to be chained on one line instead of repeated on separate lines.

Method Chaining with *this

Returning a reference to *this lets the caller write c.setRadius(5).setColor('r') instead of two separate statements.

  • Return type must be a reference to the class: Circle&
  • At the end of the function, return *this; (dereference the pointer to get the object)
  • The caller can then chain further calls on the returned reference
  • Common in builder-style APIs and stream operators

Method Chaining

C++

Each setter returns *this so the next call can be appended directly.

Const Member Functions

Marking a member function const after its parameter list tells the compiler that the function will not modify any member variable. This is the correct way to declare getters and any pure read operation. It also allows the function to be called on const objects.

const Member Function

Mark every getter and read-only function as const. It enforces the contract that the function is purely observational and safe to call on any object.

  • Syntax: double getRadius() const { return radius; }
  • The const goes after the closing parenthesis, before the function body
  • Inside a const function, the compiler treats this as a pointer to const, any attempt to modify a member is a compile error
  • A const object can only call const member functions

const Member Functions on a Circle

C++

getRadius(), area(), and circumference() are read-only and callable on const objects. setRadius() is not.

The Complete Circle Class

Putting it all together: private data, a parameterized constructor, const getters, a validated setter using this->, and read-only computation functions, all in one clean class.

Encapsulated Class Design

A well-designed class hides its data, validates all input at the boundary, and marks every read operation as const.

  • Private members: radius hidden from direct access
  • Parameterized constructor initializes state on creation
  • Setter uses this->radius to resolve the name conflict and validates before storing
  • Getters and computation functions are const: they promise not to change the object

Complete Circle Class

C++

Private data, this-> in the setter, and const on every read-only function.

Knowledge Check

1. Which access specifier makes a member visible only inside the class itself?

2. Which access specifier allows access from the class and its derived (child) classes, but not from outside?

3. What is encapsulation?

4. What does the this pointer refer to?

5. When is this->radius necessary instead of just radius?

6. What does a const member function guarantee?

7. Where does the const keyword go in a const member function declaration?

8. What is a getter function?