user1372984
user1372984

Reputation:

Defining member functions of a class?

I am working with a book on c++ and to solve the problems I am always asked to declare the member functions' prototypes in the xxxxxx.h file and define the functions body properly in the xxxxxx.cpp file. Is there any harm or disadvantage in defining the member functions in the .h file? If not, is there any benefit or advantage in defining them in the .cpp file?

Upvotes: 2

Views: 1302

Answers (2)

Andrew
Andrew

Reputation: 24846

If you will always write your code in .h files you will never be able to performa some technics, such as forward declaration. Since you can't use forward declaration if writing code in headers you will be not able to solve cross dependencies.

So you will need to include everything you need in .h file. Including this file in other file will include everything already included. Thus any small change in you code will result in almost full recompilation in many cases.

Also it's harder to read the code in .h files because you expect to see the interface of the class in .h, not implementation.

Upvotes: 3

Luchian Grigore
Luchian Grigore

Reputation: 258548

If you define the method in the header, you have to mark it as inline or define them inside the class definition to prevent multiple definitions:

//A.h
class A
{
    void f()
    {
    }
    void g();
};
inline void A::g() 
{
};

Other than that, it's a matter of coding style. You generally keep your headers clean, as to only provide an interface to work with the class, and abstract away the implementation details.

Generally. There are cases where you have to define the functions in the header (templates) or when you want to (to allow better compiler optimizations).

Upvotes: 3

Related Questions