Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Namespaces vs. Header files

I'm asking about the best practice widely used in C++ projects. I need to have my own types in the project. It's a collection of couple of typedefs.

Is including header file containing the types good practice in C++ or is it better to use namespaces. If so, why? What are the pros and cons of the two ways?

Right now it looks like this:

types.h:

#ifndef TYPES_H
#define TYPES_H

#include <list>

// forward declaration
class Class;

typedef int TInt;
// ...
typedef std::list<Class> class_list;

#endif

class.h:

#ifndef CLASS_H
#define CLASS_H

#include "types.h"

class Class
{
    public:
        // ...

        TInt getMethod();
    private:
        // ...
};

How would it look like with namespaces?

like image 688
JTom Avatar asked Dec 08 '22 03:12

JTom


1 Answers

The two concepts are orthogonal; comparing them the way you ask makes no sense.

Unless you only use these types in a single file, you have to place them in a header so you can easily bring in their definitions when you need them. Then, within that header, you can include your namespace:

#ifndef TYPES_H
#define TYPES_H

#include <list>

namespace MyNamespace {
  // forward declaration
  class Class;

  typedef int TInt;
  // ...
  typedef std::list<Class> class_list;
}

#endif

Then later you can do, for instance, MyNamespace::TInt rather than int after you #include "Types.h"

like image 76
Dennis Zickefoose Avatar answered Dec 09 '22 17:12

Dennis Zickefoose