2

I am new at C++ language and I am trying to understand why the next thing is happening:

I have a header file header.h

namespace myNamespace{
class myClass{
    public:
        myClass();
        ~myClass();
        void myFunction(void);
}

void myVoid();
}

The definitions are in header.cpp

using namespace myNamespace;

void myClass::myFunction(void){
//DO anything
}

void myVoid(){
//Do anything
}

And in the main.cpp I have the follow:

#include "header.h"

main(){
  myVoid();
  myNamespace::myVoid();
}

Why If I try to call myFunction of the class myClass from the main I have a successful compile, and if I try to call the function as in the main file I have an undefined reference error? I can fix it if in the header.h moves myVoid out of the namespace.

Why is this happening? I am trying to figure out how this works.

Thanks in advice,

D Adalid
  • 33
  • 1
  • 4
  • 1
    There isn't enough information in `void myVoid(){ }` for the compiler to tell that `myVoid` is supposed to be `myNamespace::myVoid` and not just plain old `myVoid`, so plain old `myVoid` is what goes into the compiled object file and `myNamespace::myVoid` is left unimplemented. Can't find line and verse to back this up, but someone will be along eventually with a standard quote and a real answer. – user4581301 Aug 08 '18 at 18:05
  • What is the compile error and which line? The example doesn't show a call of `myFunction`. The example is inconsistant with the question. – Robert Andrzejuk Aug 08 '18 at 18:35

1 Answers1

0

If you don't specify definition of myVoid (I mean just declaring it like you did), then the compiler can never be sure if you are implementing the function which is declared in namespace or just defining a new one.

On the other hand, if you are defining myClass::myFunction, it has to be the method that is declared in the defined class.

To make it clear, investigate the following code and take a look here (very similar question)

namespace Test { 
    int myVoid(void);    // declaration
    class yourClas;      // declaration

    class myClass{       // definition
        public:
            myClass();
            ~myClass();
            void myFunction(void); // declaration which belongs to defined class
    }
}

void myVoid() {  
// definition, but compiler can't be sure this is the function 
// that you mention in the namespace or a new function declaration.  
}

void myClass::myFunction(void){ 
// absolutely definition for the method of the corresponding class 
}
eneski
  • 1,575
  • 17
  • 40