Aamir Altaf Kathu
Aamir Altaf Kathu

Reputation: 157

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;
}

Upvotes: 0

Views: 238

Answers (3)

CashCow
CashCow

Reputation: 31435

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.

Upvotes: 0

Dirk
Dirk

Reputation: 1849

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...

Upvotes: 0

ForEveR
ForEveR

Reputation: 55887

One function for all objects of type.

Upvotes: 1

Related Questions