Rafael Vergnaud
Rafael Vergnaud

Reputation: 111

Member function vs friend functions: why one and not the other?

Why are functions of objects generally defined as class member functions instead of friend functions (with the associated instantiated object passed in as a parameter)?

If you implement push_back(vector v, val), front(vector v), back(vector) as friend functions that take as a parameter a vector, for example, would that not save on space, because the functions would not have to be defined each time a vector object is created, but only once?

I'm sorry if my question doesn't make much sense. I'm new to coding and I am not completely comfortable with its jargon/terminology. If I need to reword my question because it is unclear, please let me know.

Thank you :)

Upvotes: 2

Views: 359

Answers (2)

eerorika
eerorika

Reputation: 238351

If you implement push_back(vector v, val), front(vector v), back(vector) as friend functions that take as a parameter a vector, for example, would that not save on space, because the functions would not have to be defined each time a vector object is created, but only once?

Functions are not "defined each time a vector object is created". You don't save space by using friend functions as such.

The advantages of member functions mostly revolve around inheritance. Member functions can have protected access, and they can be virtual etc.

Friend functions are useful in implementing symmetric binary (i.e. two-argument, counting this) functions. As a member function the first argument would be special and cannot be treated equally. Furthermore, friend functions can provide an API compatible with C, which is useful for cross-language programming and shared libraries.

Upvotes: 1

Alecto
Alecto

Reputation: 10740

Unless they’re virtual, member functions don’t take up any space inside a class. And virtual member functions only take up constant space. This is usually 8 bytes, independent of how many virtual functions the class has. This is because classes with virtual functions contain a pointer to a vtable which looks up the actual function at runtime.

That being said, having friend functions at namespace scope is useful because it allows you to make overload sets. An overload set is just the name for all the overloads of a particular function name. For example, std::to_string is an overload set because there are multiple functions with that name.

Overload sets are a really useful concept because they allow you to write generic code that can act on a lot of different types, even if those types are completely unrelated For example, std::vector and std::list don’t inherit from each other or from a base class, but it’s easy to write templated functions that work on either of them because they share a common interface in terms of how they can be used.

Upvotes: 1

Related Questions