I am learning some COM code and the following code puzzled me.
STDMETHODIMP _(ULONG) ComCar::Release()
{
if(--m_refCount==0)
{
delete this; // how could this "suicide" deletion be possible?
return 0;
}
return m_refCount;
}
Yes. this is the similar code from here. And there I askes about how could a memeber method delete its belonging object. Now I am thinking about these 2 scenarios.
1- If I define a class without making an instance of it. Would any data related to this type exist in runtime?
2- If I only make 1 instance of the class and make the very single object commit suicide via the above code. After the object is deleted, where could the object’s methods stay? Or am I paying too much attention to the encapsulation illusion?
I am wondering whether class methods are first name-mangled and then stored in the code/text segment of the program without regard to the existence of any object of its type. So the class methods exist as long as you define them.
Edit post OP’s edit and gnud’s comment:
A class is an user defined type. The type will be available as will be a
floattype even if you don’t use any float in your code. The type information will be present. Particularly as gnud points out, if this is an abstract base class, you’d not be able to create any objects of that type but have derived class objects. The base class’s member information will be suitably copied/updated to the derived class objects (provided you have appropriate ctors defined of course).Methods are portions of executable code. Class objects have a table of all member function pointers. This table is updated when the object is created to point to the appropriate region of the binary. When the object is deleted, the binary remains, without a way to access it.
Edit: More on
delete thiswhich is perfectly legal: This is FAQ 16.15. Further, note that this is useful only in very few instances — a reference counted object is one such (as you show in your code).