0

I have multiple C++ classes in a Pacman Game project (Maze, Food, Pacman, ...). I made a namespace 'Pacman_AI' so that the classes can be seen every where in the project. However, I got an error for 'GameObject' class: "name followed by '::' must be a class or namespace name".

Here is my "GameObject.cpp" in which I get the error above:

namespace Pacman_AI{

vector <pair <int, int> > GameObject::getPoints(){
    return points;
}

string GameObject::getType(){
    return type;
}

}

I already defined my "GameObject" class in a different file "GameObject.h".

Your help is highly appreciated.

  • 1
    Did you include the header file where you declared `GameObject` – Richard Critten Apr 05 '17 at 15:38
  • Please **[edit]** your question with a [mcve] or [SSCCE (Short, Self Contained, Correct Example)](http://sscce.org) – NathanOliver Apr 05 '17 at 15:38
  • No but could you explain why should I include my header file? I have a global namespace already. – Mahmoud Arafa Apr 05 '17 at 15:43
  • 1
    @MahmoudArafa Source code files in a c++ project are not implicitly aware of each other or of each other's content. You must use [`#include`](http://en.cppreference.com/w/cpp/preprocessor/include) to specify, in each file, what headers it relies on. Namespaces cannot fulfill this function. – François Andrieux Apr 05 '17 at 15:46

1 Answers1

0

The simplest thing is to use namespace in your header files

// Foo.h
namespace Pacman_AI{

// STUFF HERE

};

and then using namespace in your .cpp files

//Foo.cpp
#include "Foo.h"

using namespace Pacman_AI;

// define your functions here
AlexG
  • 1,091
  • 7
  • 15
  • But I could remove my namespace from "Foo.h" and it will work the same as yours. – Mahmoud Arafa Apr 05 '17 at 15:47
  • I used namespaces so that I can escape from these "includes". You know like C# namespaces. – Mahmoud Arafa Apr 05 '17 at 15:48
  • 1
    @MahmoudArafa you cannot 'escape' from includes.. and why would you try to do that anyway ? – AlexG Apr 05 '17 at 15:49
  • 1
    @MahmoudArafa c++ includes and c++ namespaces preform different functions and one cannot be used as a substitute for the other. Perhaps [this question](http://stackoverflow.com/questions/6264249/how-does-the-compilation-linking-process-work) would be of interest to you. – François Andrieux Apr 05 '17 at 15:50
  • @All OK it seems like I have to read about namespaces. I just wanted it to work easier like C# namespaces, where every class is shared globally in the project. – Mahmoud Arafa Apr 05 '17 at 16:00