I'm trying to understand how C++ works under the hood in terms of how things are laid out in memory, how data members are accessed, and method calls, but find it very confusing. I could use some clarification about whether I am on the right track for some of these concepts when it comes to a very simple class involving no inheritance, virtual functions, etc.
class Foo
{
public:
Foo();
int i;
char c;
void meth(); // sets private member j
private:
int j;
SomeClass s;
friend class Bar;
};
Foo f;
Foo g;
data layout The objects would be arranged in the order they are declared, sequentially, along with their respective data members. I found a similar question here: How are objects stored in memory in C++?, but an additional question that came up is what happens if there are different access blocks, like private in addition to public? Is there any difference? Also what would it look like if one of the data members is another class, like SomeClass with its own data members?
data member access I read this is done by a pointer to the object (assuming "this" pointer) which is displaced by some amount depending on size/quantity of the members + padding. Again, is there a difference with private members and other classes? Is this also how Foo f's and Foo g's data members are known to be separate from one another ie if I did f.meth(), how does it pick the right j to change?
member vs. non-member methods When the function is called, it receives a pointer to the object that called it, the "this" pointer. This seems to be the case for a member function, but what happens if a non-member function, say something in the friend class Bar, tries to modify private member j? Then surely "this" would be a Bar object instead? So how would it find the data members in the Foo object it's trying to modify?