Access Class Members In C++ - C++ Programming Tutorial
C++ Course / Object-Oriented Programming / Access Class Members In C++

Access Class Members In C++

BLUF: Mastering Access Class Members In C++ is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Access Class Members In C++

C++ is renowned for its efficiency. Learn how Access Class Members In C++ enables low-level control and high-performance computing in the tutorial below.

C++ stands out as a robust and versatile programming language well-known for its object-oriented characteristics. Encapsulation serves as a fundamental principle within object-oriented programming (OOP), allowing us to conceal a class's internal workings and reveal only the essential functionality externally. To achieve this goal, C++ provides various access specifiers like public, private, and protected, which control the visibility of class members. In this guide, we will explore these access specifiers in C++ and grasp the methods for interacting with class members through numerous illustrative examples and detailed explanations.

Overview of Access Specifiers:

Access specifiers manage the visibility and accessibility of class elements (variables and functions) within a class. C++ offers three primary access specifiers:

Public:

Anyone can retrieve members that have been marked as public, whether within or outside the class. This access modifier provides the broadest visibility, allowing the member to be accessed from any part of the program.

Private:

Only members of the class that encapsulates them have access to private members. Private members are perfect for safeguarding internal implementation specifics as they remain hidden from external entities.

Protected:

Protected members differ slightly from private members as they can be accessed by the class itself and its derived classes. When restricting access to subclasses to a specific extent, protected members are commonly used.

Accessing Public Class Members:

Let's begin by exploring the process of accessing elements within the public class. Public members are accessible from any part of the program.

Program:

Let's consider an example to showcase how to access public class members in C++.

Example

#include <iostream>

class MyClass {
public:
    int publicVar;

    void publicFunction() {
        std::cout << "This is a public function." << std::endl;
    }
};

int main() {
    MyClass obj;
    obj.publicVar = 42;
    obj.publicFunction();

    std::cout << "Accessing publicVar from outside the class: " << obj.publicVar << std::endl;
    return 0;
}

Output

Output

This is a public function.
Accessing publicVar from outside the class: 42

Explanation:

In this instance, PublicVar and publicFunction are accessible to the public as members of the MyClass class. An object named obj of the class MyClass is instantiated within the main method. The publicVar member can be accessed, modified, and invoked externally, just like the publicFunction member.

We observe that public members are accessible to anyone, from any location, and at any moment. Therefore, they should be used for interface components that need to be accessed externally from the system.

Accessing Private Class Members:

Only the members of the class that declared them are able to access private members. Attempting to access a private member from outside the class will result in a compilation error.

Program:

Let's consider an example to illustrate how to access private class elements in C++.

Example

#include <iostream>

class MyClass {
private:
    int privateVar;

    void privateFunction() {
        std::cout << "This is a private function." << std::endl;
    }

public:
    void setPrivateVar(int value) {
        privateVar = value;
    }

    void accessPrivateFunction() {
        privateFunction();
    }
};

int main() {
    MyClass obj;
    // obj.privateVar = 42;
    obj.setPrivateVar(42);
    obj.accessPrivateFunction();

    return 0;
}

Output

Output

This is a private function.

Explanation:

In the previous example, the private attributes of the MyClass class, privateVar and privateFunction, are defined. Private members are not accessible from external sources. Hence, if the attempt to access privateVar directly is uncommented, a compilation error will occur.

We've provided the public member functions accessPrivateFunction and setPrivateVar to indirectly interact with the private members. Upholding encapsulation and controlling access to confidential information and implementation specifics are common practices in C++.

As indicated in the result, the private method privateFunction was accessible through the public member function accessPrivateFunction. Likewise, we employ the public member function setPrivateVar to assign a value to privateVar.

Accessing Members of Protected Classes:

Private and protected members share a common trait of being shielded from direct external access. Nevertheless, they diverge notably in the aspect that protected members can be accessed by derived classes, which are also known as subclasses.

Program:

Let's consider an example to showcase how to access protected class elements in C++.

Example

#include <iostream>

class MyBaseClass {
protected:
    int protectedVar;

public:
    MyBaseClass() : protectedVar(0) {}

    void setProtectedVar(int value) {
        protectedVar = value;
    }

    int getProtectedVar() const {
        return protectedVar;
    }
};

class MyDerivedClass : public MyBaseClass {
public:
    void accessProtectedVar() {
        int val = getProtectedVar();
        std::cout << "Accessing protectedVar from a derived class: " << val << std::endl;
    }
};

int main() {
    MyDerivedClass obj;

    // Attempting to access protectedVar directly from outside the class will result in an error.
    // obj.protectedVar = 42;

    // We can access protected members through derived classes.
    obj.setProtectedVar(42);
    obj.accessProtectedVar();

    return 0;
}

Output

Output

Accessing protectedVar from a derived class: 42

Explanation:

In this instance, the ProtectedVar is defined as a protected attribute within MyBaseClass. MyDerivedClass is an inherited class originating from MyBaseClass. When we instantiate a MyDerivedClass object in the main function and attempt to directly access protectedVar, it results in a compilation error.

Instead, we utilize public member functions of MyBaseClass to interact with protectedVar. The setProtectedVar function is employed to assign a value to protectedVar, while the getProtectedVar function is used to retrieve its value. Through these functions, MyDerivedClass, a derived class, gains access to protectedVar, demonstrating the functionality of the protected access specifier.

Proper usage of Access specifiers:

After going over C++'s three access specifiers , let's talk about when to utilize each one.

  • Use the public access specifier for class members that should be reachable from wherever in the program. These components of the class's interface specify how outside code can communicate with it.
  • Use the private access specifier for members that are internal to the class and should not be immediately accessed from the outside. Typically, private members are used for implementation specifics and to impose data concealment.
  • If we want to provide derived classes with restricted access, use the pr otected access specifier . It keeps unauthorized code from directly accessing the protected members while yet allowing derived classes to inherit and utilize them.
  • Conclusion:

Developing dependable and sustainable code in C++ necessitates a comprehension of and proficiency with access specifiers. By following the encapsulation principles and controlling the visibility of class members through public, private, and protected access specifiers, we can craft classes that are both effective and safeguarded.

In summary, public members define the interface of a class and can be accessed from any part of the program. Private members are reserved for internal implementation specifics and are not visible to external users. Subclasses have the ability to access protected members, providing a controlled way for derived classes to retrieve data.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience