Use app×
Join Bloom Tuition
One on One Online Tuition
JEE MAIN 2025 Foundation Course
NEET 2025 Foundation Course
CLASS 12 FOUNDATION COURSE
CLASS 10 FOUNDATION COURSE
CLASS 9 FOUNDATION COURSE
CLASS 8 FOUNDATION COURSE
0 votes
606 views
in C++ by (106k points)
retagged by
Master C++ Access Specifiers: Public, Private, and Protected | Learn how to control the visibility and accessibility of your C++ class members with access specifiers. Understand the differences between public, private, and protected keywords for effective encapsulation. Get comprehensive insights and examples to enhance your C++ programming skills.

Please log in or register to answer this question.

2 Answers

0 votes
by (106k points)

Access Specifiers in C++

Access specifiers in C++ are keywords that determine the accessibility of class members (variables and functions) from different parts of the program. They enforce encapsulation and control the level of visibility of class members. C++ provides three access specifiers:

  1. public
  2. protected
  3. private

Each access specifier has a different level of visibility and restricts access to class members in different ways.

1. Public Access Specifier

The public access specifier allows the class members to be accessed from anywhere in the program. They can be accessed by other classes, objects, or functions. Members declared as public are accessible even outside the class scope.

Here's an example code demonstrating the use of the public access specifier:

#include <iostream>

class MyClass {
public:
    int publicVar;
    
    void publicFunc() {
        std::cout << "This is a public function." << std::endl;
    }
};

int main() {
    MyClass obj;
    obj.publicVar = 10;
    obj.publicFunc();
    
    return 0;
}
 

In the above example, the publicVar variable and the publicFunc() function are declared as public members. They can be accessed directly using the object obj of the MyClass class.

2. Protected Access Specifier

The protected access specifier allows the class members to be accessed within the class itself and its derived classes. They are not accessible outside the class hierarchy.

Here's an example code demonstrating the use of the protected access specifier:

#include <iostream>

class MyBaseClass {
protected:
    int protectedVar;
    
    void protectedFunc() {
        std::cout << "This is a protected function." << std::endl;
    }
};

class MyDerivedClass : public MyBaseClass {
public:
    void accessProtectedMember() {
        protectedVar = 20;     // Accessing protectedVar from the derived class
        protectedFunc();       // Accessing protectedFunc from the derived class
    }
};

int main() {
    MyDerivedClass obj;
    obj.accessProtectedMember();
    
    return 0;
}
 

In the above example, the protectedVar variable and the protectedFunc() function are declared as protected members in the MyBaseClass. These members are accessible within the derived class MyDerivedClass, as shown in the accessProtectedMember() function.

3. Private Access Specifier

The private access specifier restricts the access of class members to the class itself. They are not accessible outside the class, including derived classes.

Here's an example code demonstrating the use of the private access specifier:

#include <iostream>

class MyClass {
private:
    int privateVar;
    
    void privateFunc() {
        std::cout << "This is a private function." << std::endl;
    }
    
public:
    void accessPrivateMember() {
        privateVar = 30;     // Accessing privateVar within the class
        privateFunc();       // Accessing privateFunc within the class
    }
};

int main() {
    MyClass obj;
    obj.accessPrivateMember();
    
    return 0;
}
 

In the above example, the privateVar variable and the privateFunc() function are declared as private members in the MyClass. These members can only be accessed within the class itself, as demonstrated in the accessPrivateMember() function.

In summary, access specifiers in C++ control the visibility and accessibility of class members. Here's a brief overview of the three access specifiers:

  • public: Members are accessible from anywhere in the program.
  • protected: Members are accessible within the class and its derived classes.
  • private: Members are only accessible within the class itself.

Understanding and properly using access specifiers is essential for implementing encapsulation and ensuring the proper access levels of class members in C++ programs.

0 votes
by (106k points)

FAQs on C++ Access Specifiers

Q: What are access specifiers in C++? 

A: Access specifiers in C++ are keywords used to control the visibility and accessibility of class members (data members and member functions) from different parts of the program. The three access specifiers in C++ are public, private, and protected.

Q: What is the default access specifier in C++? 

A: The default access specifier for class members in C++ is private. If you don't specify an access specifier explicitly, class members are considered private by default.

Q: What does the public access specifier mean in C++? 

A: The public access specifier allows class members to be accessed from anywhere in the program. Public members are visible to all code that has access to the class.

Example:

class MyClass {
public:
    int publicVar;
    void publicMethod() {
        // Code for the public method
    }
};

int main() {
    MyClass obj;
    obj.publicVar = 42;  // Accessing public member variable
    obj.publicMethod();  // Calling public member function
    return 0;
}
 

Q: What does the private access specifier mean in C++? 

A: The private access specifier restricts the access of class members only to the class itself. Private members cannot be accessed or modified directly from outside the class.

Example:

class MyClass {
private:
    int privateVar;
    void privateMethod() {
        // Code for the private method
    }
public:
    void accessPrivate() {
        privateVar = 10;  // Accessing private member variable
        privateMethod(); // Calling private member function
    }
};

int main() {
    MyClass obj;
    obj.accessPrivate(); // Accessing private members indirectly
    return 0;
}
 

Q: What does the protected access specifier mean in C++? 

A: The protected access specifier is similar to private, but it also allows access to derived classes. Protected members are not accessible from outside the class, but they can be accessed by derived classes.

Example:

class BaseClass {
protected:
    int protectedVar;
    void protectedMethod() {
        // Code for the protected method
    }
};

class DerivedClass : public BaseClass {
public:
    void accessProtected() {
        protectedVar = 20;  // Accessing protected member variable
        protectedMethod(); // Calling protected member function
    }
};

int main() {
    DerivedClass obj;
    obj.accessProtected(); // Accessing protected members in derived class
    return 0;
}
 

These examples demonstrate how access specifiers control the visibility and accessibility of class members in C++. Remember to choose the appropriate access specifier based on your desired level of encapsulation and access requirements.

Important Interview Questions and Answers on C++ Access Specifiers

Q: What are access specifiers in C++?

Access specifiers are keywords used in C++ to define the visibility and accessibility of class members (variables and functions) within the class and from outside the class. C++ provides three access specifiers: public, private, and protected.

Q: What is the default access specifier in C++?

The default access specifier in C++ is "private". If you don't specify an access specifier for class members, they are considered private by default.

Q: What is the difference between public, private, and protected access specifiers in C++?

  • Public: Public members are accessible from anywhere, both within and outside the class.
  • Private: Private members are only accessible within the class. They are not accessible from outside the class, even from derived classes.
  • Protected: Protected members are accessible within the class and from derived classes. They are not accessible from outside the class.

Q: Can you provide an example of using public access specifier in C++?

Sure! In the following example, we have a class called "Person" with a public member function "greet()". The "greet()" function can be accessed from anywhere, including outside the class.

class Person {
public:
    void greet() {
        std::cout << "Hello, I am a person!" << std::endl;
    }
};

int main() {
    Person p;
    p.greet();  // Calling public member function
    return 0;
}
 

Q: Can you provide an example of using private access specifier in C++?

Certainly! In the following example, we have a class called "BankAccount" with a private member variable "balance". The "balance" variable is only accessible within the class and cannot be accessed from outside.

class BankAccount {
private:
    double balance;

public:
    void deposit(double amount) {
        balance += amount;
    }

    void withdraw(double amount) {
        if (amount <= balance)
            balance -= amount;
        else
            std::cout << "Insufficient balance!" << std::endl;
    }
};

int main() {
    BankAccount account;
    account.deposit(1000);  // Accessing public member function
    account.withdraw(500);  // Accessing public member function
    // account.balance = 10000;  // Error: Cannot access private member directly
    return 0;
}
 

Q: Can you provide an example of using protected access specifier in C++?

Certainly! In the following example, we have a base class called "Shape" with a protected member variable "color". The "color" variable is accessible within the class and can also be accessed by derived classes.

class Shape {
protected:
    std::string color;
};

class Circle : public Shape {
public:
    void setColor(const std::string& c) {
        color = c;
    }

    void printColor() {
        std::cout << "Color: " << color << std::endl;
    }
};

int main() {
    Circle c;
    c.setColor("Red");  // Accessing protected member through derived class
    c.printColor();     // Accessing public member function
    return 0;
}
 

These examples demonstrate the usage of access specifiers in C++ and how they control the visibility and accessibility of class members.

Related questions

0 votes
1 answer
asked Jun 7, 2023 in C++ by kvdevika (106k points)
0 votes
1 answer
0 votes
1 answer

Welcome to Sarthaks eConnect: A unique platform where students can interact with teachers/experts/students to get solutions to their queries. Students (upto class 10+2) preparing for All Government Exams, CBSE Board Exam, ICSE Board Exam, State Board Exam, JEE (Mains+Advance) and NEET can ask questions from any subject and get quick answers by subject teachers/ experts/mentors/students.

Categories

...