简体   繁体   中英

Are separate functions created for each object or only one per class?

For example in the following code, is a copy of func1() created for each obj1 , obj2 ? Or is a single copy of func1 shared between them?

class ABC
{
    int a;
    public:
        void  func1(void)
        {
            int k = 9;
            cout << "k = " << k;
        }
};
int main()
{
    ABC Obj1,Obj2;
    ......
    return 0;
}

一种针对所有类型对象的功能。

Basically, each method exists only once as if you would have a normal c-style function to which a pointer is given:

    void func1(ABC *this)
    {
        int k = 9;
        cout << "k = " << k;
        this->a = 42;
    }

    ABC obj1;
    func1(&obj1);

This is only true as long you don't use inheritance with overloading. When using inheritance with overloading, a so called vtable comes into play, but that's another lesson...

If you take the address of the function &ABC::func1 it will always be the same address. It will not be different for each instance of ABC.

Note that it is a pointer to a function, and it always points to the same place.

Virtual functions have a different method of dispatch, where each derived class holds a table (v-table or virtual table) to what exact function is called for each one.

The obvious way to show this is in the language's bind function where you can do this:

std::function< void() > = std::bind( &ABC::func1, std::placeholders::_1 );

and you can subsequently pass in pointers / references to your Obj1 , Obj2 or Obj3 to that std::function

Having said that there is only one function, do not be confused to think that it is not thread-safe. Each time the function is invoked, there is a separate local instance of the variable k . This local variable is created new on the stack each time the function is invoked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM