What are access specifiers in C++?
Why Interviewers Ask This
This question tests conceptual clarity. Interviewers want to hear a precise, confident definition before moving to more complex C++ topics. It also reveals how well you can explain technical ideas to non-experts.
Answer
C++ has three access specifiers that control the visibility of class members: (1) public: accessible from anywhere — inside the class, derived classes, and external code. class Car { public: std::string brand; // Any code can access void drive() {} // Any code can call };; (2) private: (default for class) accessible only within the class itself and friend classes/functions. Not accessible from derived classes: class BankAccount { private: double balance = 0; // Only BankAccount methods can access public: void deposit(double a) { balance += a; } // OK double getBalance() const { return balance; } // OK };; (3) protected: accessible within the class and its derived classes, but NOT from external code: class Animal { protected: std::string name; // Accessible in Dog, Cat, etc. }; class Dog : public Animal { void bark() { std::cout << name; } // OK -- protected access };. In structs: default access is public (everything else same as class). Inheritance and access: public inheritance preserves public/protected access; protected inheritance makes public members protected; private inheritance makes all inherited members private. Friend functions/classes: declared inside a class with friend keyword — bypass access restrictions. Use sparingly as they break encapsulation: class Box { private: double volume; friend double calcVolume(const Box& b); };. Getters/setters: expose controlled access to private data: double getBalance() const; void setName(std::string n);.
Common Mistake
A common mistake is memorizing definitions without understanding implications. When asked this question, go one level deeper — explain what happens when this concept is misused or ignored.
Previous
What are virtual functions and polymorphism in C++?
Next
What is the Standard Template Library (STL)?