What is the benefit of declaring a function outside class in c++? [duplicate]
Asked Answered
O

1

6

I am fairly new to C++. I encountered two ways of declaring member functions in c++, ie. Inside class and Outside Class. I searched about the differences and it says the functions that are defined inside class are treated as inline functions.

When I previously read about inline functions it stated that inline is just a request to the compiler to substitute function body instead of calling the functions. But if the function is complex (like recursive, contains static variables, switch etc.) then the compiler will ignore the request. So even if we declare the function inside class if it is complex compiler will ignore the request. Then what is the point of defining functions outside class, if we can just let this decision on compiler itself to automatically do it for us?

Ornithischian answered 6/11, 2019 at 16:14 Comment(5)
There are many reasons for that. It is not important to you to understand all those reasons now. As you continue to go along with your C++ studies, and become more knowledgeable and skilled with C++, you will automatically learn and recognize the many differences between either approaches. Don't waste your time focusing on these trivialities at this time, and stay focused on learning the language.Molal
related/dupe: #9076431. Just define them outside so your class isn't so big you can't read it.Jaclin
inline has little to do with actual inlining and more to do with ODR (One Definition Rule).Selfforgetful
Don't forget that often you need to pass around the interface to the class, the definition, but for one reason or another can't pass around how the class works.Anjanette
@FedericoklezCulloca Functions defined in a class declaration are implicitly inline. You can read that straight out of the C++ standard.Selfforgetful
C
7

Defining a complex member function in a class makes the class definition too complicated and not well-readable.

Bear in mind that you can declare a member function with the function specifier inline without its definition within the class.

Take into account that if the compiler will make non-inline calls of a member function of a class defined within the class nevertheless all other requirements to the function will be the same as for an inline function. For example the function definition with the class definition can be included in many compilation units.

Defining a member function outside a class allows to separate the interface and its realization.

Choroid answered 6/11, 2019 at 16:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.