object instantiation in c++

2019-07-27 01:38发布

In C++ is it true that if you instantiate an object of a class, that for every object all of methods of the class are copied for the new object?

I tried to point to a method of a class with two different objects, but I'd problems with pointer to member.

Any idea?

3条回答
不美不萌又怎样
2楼-- · 2019-07-27 02:18

The code for a class exists only once.

For getting a pointer to a member function (probably what you meant by method), take a look at std::function, and for attaching the function call to different objects, take a look at std::bind.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-07-27 02:36

No, that is absolutely not true.

Class instances (objects) contain data members. Function members look like they're "in" the class, but that's only for scoping and such: your function code doesn't "exist" inside the type, and it certainly doesn't exist inside the object.


I think it could, theoretically, in that the standard doesn't outright forbid it. But honestly, no. Just no.

查看更多
老娘就宠你
4楼-- · 2019-07-27 02:37

In C++ is it true that if you instantiate an object of a class, that for every object all of methods of the class are copied for the new object?

No, member functions are not usually copied anywhere. A different implicit parameter this is instead passed to any non-static member function, for each object of that class-type.

查看更多
登录 后发表回答