C++ Access Specifiers (public, private, protected) & Friend Functions

Access specifiers define the visibility and accessibility of class members from outside the class boundary, serving as the primary mechanism for Encapsulation.

The 3 Access Specifiers

  • public: Accessible from anywhere in the program.
  • protected: Accessible only inside the class and its derived (child) subclasses.
  • private: Accessible strictly within the class itself (and designated friends).

Friend Functions Demonstration

#include <iostream>

class Box {
private:
    double width;

public:
    Box(double w) : width(w) {}

    // Declare a friend function granting access to private width
    friend void printWidth(const Box& b);
};

// Standalone function with access to private members of Box
void printWidth(const Box& b) {
    std::cout << "Box private width is: " << b.width << "\n";
}

int main() {
    Box box(25.4);
    printWidth(box); // Allowed!
    return 0;
}

Frequently Asked Questions (FAQ) - Student & Interview Review

Q1. What is the difference between private and protected access in C++?

Private members can ONLY be accessed by member functions and friend classes of the class in which they are declared. Protected members can be accessed by the class itself AND by any derived (child) classes through inheritance.

Q2. Does a 'friend' function violate encapsulation?

No. A friend function is explicitly granted access by the author of the class inside the class declaration. It is often necessary for non-member operator overloading (e.g., std::ostream& operator<<(std::ostream&, const MyClass&)).

Explore Related C++ Tutorials & Next Steps

Boost your C++ proficiency by studying these closely connected core modules:

C++ Inheritance

How access specifiers change in derived classes.

Classes & Objects

Setting up private fields and public methods.

Operator Overloading

Using friend functions to overload stream << and >>.

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!