Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

class member access specifiers and binary code

I understand what the typical access specifiers are, and what they mean. 'public' members are accessible anywhere, 'private' members are accessible only by the same class and friends, etc.

What I'm wondering is what, if anything, this equates to in lower-level terms. Are their any post-compilation functional differences between these beyond the high-level restrictions (what can access what) imposed by the language (c++ in this case) they're used in.

Another way to put it - if this were a perfect world where programmers always made good choices (like not accessing members that may change later and using only well defined members that should stay the same between implementations), would their be any reason to use these things?

like image 202
pdehaan Avatar asked May 03 '10 16:05

pdehaan


2 Answers

Access specifiers only exist for compilation purposes. Any memory within your program's allocation can be accessed by any part of the executable; there is no public/private concept at runtime

like image 68
Michael Mrozek Avatar answered Oct 18 '22 23:10

Michael Mrozek


Michael's answer is right. Access specifiers do not directly affect the resulting code.

However, access specifiers may resolve ambiguous identifier/overload errors that would otherwise prevent compilation.

class A {
private:
    int x;
};

class B {
protected:
    int x;
};

class C : public A, public B {
public:
    int &get_x() { return x; } // only B::x is accessible, no error.
};

So they definitely serve a higher purpose than restricting the programmer.

like image 2
Potatoswatter Avatar answered Oct 18 '22 22:10

Potatoswatter