0

I'm sort of new to C++, and I've been making my way through a bit in my own project. I ran into an error with this header and .cpp file


// main.cpp

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

int main() {
    MyClass::TestFunction(); //'MyClass::TestFunction': illegal call of non-static member function
}

// header.h

#ifndef HEADER_H
#define HEADER_H

#include <iostream>

class MyClass {
public:
    void TestFunction() {
        std::cout << "Hello World\n"; //Where I beleive the issue is
    }
};

#endif

Now I think the issue comes from std::cout not being static and the declaration in main.cpp needs it to be static, but I'm not sure how to make it static so that main.cpp works correctly. If anyone could give me a tip as to how I can make things like this work later on down the road, that would be awesome :)

Tim Rowland
  • 37
  • 1
  • 7
Gman0064
  • 107
  • 3
  • 13
  • 3
    Possible duplicate of [The Definitive C++ Book Guide and List](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) – LogicStuff Oct 11 '16 at 07:46
  • The issue is that `TestFunction` is not static, but you called it using the syntax for calling a static function. – M.M Oct 11 '16 at 07:52

2 Answers2

3

the issue comes from std::cout not being static and the declaration in main.cpp needs it to be static

You either have to make your function static OR to intanciate an object of your class and hen call its function :

main.cpp

int main() {
    MyClass pony;
    pony.TestFunction();
}

OR

header.h

class MyClass {
public:
    static void TestFunction() {
        std::cout << "Hello World\n";
    }
};
Treycos
  • 7,373
  • 3
  • 24
  • 47
  • 1
    `return 0;` is redundant, `main` is defined to return `0` if execution reaches the end – M.M Oct 11 '16 at 07:52
  • 1
    Only use `std::endl` if you _need_ to flush the buffer, `\n` is way faster otherwise. – Hatted Rooster Oct 11 '16 at 07:54
  • Thank you for explaining it to me. Looking back, I'm pretty stupid for not adding `static` behind the `void` to make it static! Simple fix that I've done hundreds of times before in C#! – Gman0064 Oct 11 '16 at 17:29
1

whenever a member function is written inside a class, it can be called only using object. You have to create a object in main function.

// main.cpp

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

int main() {
    MyClass myObject;
    myObject.TestFunction(); //'MyClass::TestFunction': illegal call of non-static member function }

OR If you dont want to use object, then make the member function as static.

// header.h

#ifndef HEADER_H
#define HEADER_H

#include <iostream>

class MyClass {  public:
    void static TestFunction() {
        std::cout << "Hello World\n"; //Where I beleive the issue is
    } };

#endif
raj.ini
  • 56
  • 3