Accessing private member variables of a class from a static method

I am able to access the private member variable of the class shown in below code directly using an object instance (pointer to object). As per my understanding private members should not be accessible. Can someone please help to explain the reason behind this behaviour ?

#include <iostream>

class myClass;
using myClassPtr = std::shared_ptr<myClass>;

class myClass {
public:
    myClass(unsigned int val) : m_val(val) {}
    ~myClass() {}

    static
    myClassPtr create(unsigned int val) {
        myClassPtr objPtr = nullptr;
        objPtr = std::make_shared<myClass>(val);
        if(objPtr) {
            std::cout << objPtr->m_val << std::endl;
        }
        return objPtr;
    }
private:
    unsigned int m_val;
};

int main () {
    myClassPtr objPtr = myClass::create(10);
    return 0;
}

Output

anandkrishnr@anandkrishnr-mbp cpp % g++ static_test.cc -std=c++11 -Wall -Werror
anandkrishnr@anandkrishnr-mbp cpp % ./a.out
10

>Solution :

static myClassPtr create(unsigned int val) {

create() is a static method of myClass, it is a member of this class. As such it it entitled to access all private members and methods of its class. This right extends not only to its own class instance, but any instance of this class.

As per my understanding private members should not be accessible.

… except by members of their class.

Let’s create a completely pointless copy constructor for your class, the same copy constructor you would get by default:

myClass(const myClass &o) : m_val{o.m_val} {}

This copy constructor has no issues, whatsoever, of accessing m_val of the passed-in object. Exactly the same thing happens here. m_val is a private member of its class. It doesn’t mean that only an instance of the same exact object can access its private members, it means that any instance of the class, or a static class method, can access the private class members.

Leave a Reply