Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I use both header files and cpp/source files?

I have a Mammal.h file that reads:

#ifndef MAMMAL_H
#define MAMMAL_H

class Mammal
{
public:
    void Speak();
};

#endif

My CPP file looks like:

#include "stdafx.h"
#include "Mammal.h"
#include <iostream>

void Mammal::Speak()
{
    using namespace std;

    cout << "Speaking";
}

And my use of this code is seen here:

#include "stdafx.h"
#include "Mammal.h"

int main()
{
    Mammal *mammal = new Mammal();

    mammal->Speak();
}

However, I could do this in the header file:

#include "stdafx.h"
#include <iostream>

#ifndef MAMMAL_H
#define MAMMAL_H

class Mammal
{
public:
    void Speak()
    {
        using namespace std;

        cout << "Speaking";
    }
};

#endif

I haven't really defined a preference...but I do see that both work. Are there advantages or disadvantages to either of these approaches?

like image 291
LunchMarble Avatar asked Jan 27 '26 16:01

LunchMarble


2 Answers

Try calling that code from more than one place -- and therefore #including the header in more than one source file -- and you'll see the problem in the second approach. The linker doesn't like it if you have more than one definition of the same function, even if they're identical.

like image 129
Beta Avatar answered Jan 30 '26 06:01

Beta


Beta is correct that defining your functions in the header file will cause problems when your header is included in multiple files.

I would also suggest that you separate the header and implementation into separate files as just a good coding practice. The header file represents the "interface" of the class. The public functions are what are available to the users of the class, and the header provides a concise way for people to see the functions without having to care about the implementation. Also, this gives you the ability to change the implementation without affecting the callers, because they only include the header, and the implementation typically is just a library that gets linked in.

like image 42
Andy White Avatar answered Jan 30 '26 05:01

Andy White