Classes and instances

Hello!

When I create a class , lets say Person which includes:
private:
Id and name.
public:
ctor, copy ctor, three member functions.

What does the compiler do everytime I create an instance of person? what happens behind the scenes?

I know that it calls the ctor first to create the object, but how does it "connect" the object with the member functions? does it create separate member functions for each object created..? I guess not. what does it do then?

I would love to get a good explanation for that!!

thank you
It's pretty easy: When a member function is called the first invisible parameter is the pointer to the surrounding object. The name of the paramater is this. member variables are accessed (again invisibly) via the this pointer

1
2
3
4
5
6
class foo
{
  void bar(int x);

  int y;
}

1
2
3
4
void foo::bar(int x)
{
  y = x;
}
resolves to
1
2
3
4
void bar(foo *this, int x)
{
  this->y = x;
}


1
2
3
4
5
int main()
{
  foo obj;
  obj.bar(1);
}
resolves to
1
2
3
4
5
int main()
{
  foo obj;
  bar(&obj, 1);
}
So, all of the class's member functions are created the first time I create an instance of a class? And then when I create a second instance it uses the first's ?
functions (no matter whether they are member of a class/struct or not) exist only once within the whole program. You do not create them

As I said:
void foo::bar(int x) is equivalent to void bar(foo *this, int x)

A function is not an object so it doesn't need to be created like one. A (non-virtual) member function works the same as other functions.
Got it. thank you very much.
Topic archived. No new replies allowed.