Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How is access for private variables implemented in C++ under the hood?

How does the compiler control protection of variables in memory? Is there a tag bit associated with private variables inside the memory? How does it work?

like image 502
Sharat Chandra Avatar asked Jul 14 '12 19:07

Sharat Chandra


People also ask

Can public methods access private variables?

But after the object is created you can only access the private variable through the public methods of the constructor and no longer change it directly in any way.

Can an object access a private member function?

Private: The class members declared as private can be accessed only by the functions inside the class. They are not allowed to be accessed directly by any object or function outside the class.

How do you use a private member variable in C++?

A private member variable or function cannot be accessed, or even viewed from outside the class. Only the class and friend functions can access private members. class Box { double width; public: double length; void setWidth( double wid ); double getWidth( void ); };

Why do we use private variables in C++?

private data members are generally considered good because they provide encapsulation. Providing getters and setters for them breaks that encapsulation, but it's still better than public data members because there's only once access point to that data. You'll notice this during debugging.


1 Answers

If you mean private members of instances, then there's no protection whatsoever at run-time. All protection takes place at compile-time and you can always get at the private members of a class if you know how they are laid out in memory. That requires knowledge of the platform and the compiler, and in some cases may even depend on compiler settings such as the optimization level.

E.g., on my Linux/x86-64 w/GCC 4.6, the following program prints exactly what you expect. It is by no means portable and might print unexpected things on exotic compilers, but even those compilers will have their own specific ways to get to the private members.

#include <iostream>

class FourChars {
  private:
    char a, b, c, d;

  public:
    FourChars(char a_, char b_, char c_, char d_)
      : a(a_), b(b_), c(c_), d(d_)
    {
    }
};

int main()
{
    FourChars fc('h', 'a', 'c', 'k');

    char const *p = static_cast<char const *>(static_cast<const void *>(&fc));

    std::cout << p[0] << p[1] << p[2] << p[3] << std::endl;
}

(The complicated cast is there because void* is the only type that any pointer can be cast to. The void* can then be cast to char* without invoking the strict aliasing rule. It might be possible with a single reinterpret_cast as well -- in practice, I never play this kind of dirty tricks, so I'm not too familiar with how to do them in the quickest way :)

like image 161
Fred Foo Avatar answered Sep 28 '22 08:09

Fred Foo