-2

I have a a Class (MethodClass.h & MethodClass.cpp files) and a main.cpp

In main I'm calling the constructor and then a method.

Constructor is working fine but for the method I get the Error: "Test/main.cpp:13: undefined reference to `MethodClass::testMethod()'"

I simplified the problem with this test-project:

MethodClass.h

#ifndef METHODCLASS_H
#define METHODCLASS_H

#include <cstdlib>
#include <iostream>

class MethodClass {
public:
    MethodClass();
    MethodClass(const MethodClass& orig);
    virtual ~MethodClass();

    void testMethod();
private:

};

#endif /* METHODCLASS_H */

MethodClass.cpp:

#include "MethodClass.h"

using namespace std;

MethodClass::MethodClass() {
    cout << "Constructor: MethodClass" << endl;
}

MethodClass::MethodClass(const MethodClass& orig) {}

MethodClass::~MethodClass() {}

void testMethod(){
    cout << "testMethod" << endl;
}

main.cpp:

#include <cstdlib>
#include "MethodClass.h"

#include "MethodClass.h"
using namespace std;

int main(int argc, char** argv) {

    MethodClass mClass = MethodClass();

    cout << "hallo" << endl;

    mClass.testMethod();

    return 0;
}
  • The problem is with the last line in the main.cpp: mClass.testMethod();

If i rem this, the constructor works fine - result : Constructor: MethodClass hallo

  • Also very strange I don't even have to include the "MethodClass.h" in the main.cpp...

If I rem the first line as well: //#include "MethodClass.h", it's still fine, is this normal or can you explain to me why this works?

Btw: I'm Using Netbeans 8.0.2 with MinGW Compiler

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Guti_Haz
  • 2,528
  • 2
  • 15
  • 20

1 Answers1

4

Change your implementation of testMethod to the following:

void MethodClass::testMethod(){
    cout << "testMethod" << endl;
}

You need to properly scope all functions defined in the .cpp file. void testMethod() is just a global function testMethod() with no container class.

E. Moffat
  • 3,165
  • 1
  • 21
  • 34
  • Oke, thanks - that was it... I guess years of none c/c++ and hours of syntax warring dazed my sight a little... Sry, for this question, here have a link to a hot potatoe... http://tinyurl.com/nkyaymp Though downvotes, really? – Guti_Haz Jan 17 '15 at 00:46
  • I an new to c++ I have the same problem I have the method name prefixed with the class name in the .cpp file but I still get the same error in the main file, can you tell me how to fix it please – HII Jun 12 '20 at 20:09
  • @LoVe If you define a method in a class such as `class MethodClass { void testMethod(); };`, the CPP file needs to have `void MethodClass::testMethod() { }`. Make sure your cpp files include the proper headers too. – E. Moffat Jun 15 '20 at 16:15