object instantiation in c++

ぃ、小莉子 提交于 2019-12-11 05:08:02

问题


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?


回答1:


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.




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/21316374/object-instantiation-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!