Now I have been learning about inline functions and I encountered something that really made me confused
See this class
class Nebla{
private:
int x;
public:
inline void set(int y){x=y;}
inline void print(){cout<<x<<endl;}
};
it has a private data member: int x;
And it has two public inline functions: set(int y)
and print()
Now since they two functions are inline, when they are called the compiler replaces the function call with the contents of the function.
So if I do this
Nebla n;
n.set(1);
n.print();
since the two functions are inline, It should be the equivalent of this:
Nebla n;
n.x=1;
cout<<n.x<<endl;
but wait a second, x
is private. Therefore, this shouldn't work.
But it does and I'm confused why it does work although normally you cant access private members from outside the class?
Can anyone explain to be why you can access private data members from outside the class but when a member function is inline it can although inline just replaces the function call with the contents of the function?
Data member protection is purely conceptual. It exists only at the compiler level. It is checked and enforced when the compiler translates the source code. Once the code is compiled, there's no difference between public and private data members anymore, i.e. there are no physical mechanisms that would enforce access control and prevent access to private data members.
Member access is enforced by the compiler in accordance with the language specification. The language specification states that class member functions (regardless of whether they are inline or not) have access to private members of the class. So the compiler allows that access. Meanwhile, other functions are prohibited such access, so the compiler complains about it.
In your example you are accessing private data member from a member function. That is allowed, so the code compiles, i.e. the compiler does not complain. What happens later in the generated machine code, after the function gets inlined, is completely irrelevant. That's all there is to it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With