Quick Question

First: I am using C++ in Unix.

I have 2 header files (2 .h and 2 .cpp's) and then my main.cpp.
I have a STUDENT.h , STUDENT.cpp , CLASS.h , and CLASS.cpp . I'm including my headers in each other (my CLASS.cpp is including STUDENT.h and vice versa).

Now, I have a simple if statement for my program's menu.
It's simply:

In STUDENT.cpp (it's not the only thing in there. It's about 600 lines of code. ha)
1
2
3
if (option == "3"){
     CLASS::find();
}


In CLASS.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#ifndef CLASS_H //guards the header
#define CLASS_H
#include <vector> //includes the vector library
#include <string> //includes the string library

class CLASS { //starts the CLASS class
        private:        //private section for variables the user does not need access to
                std::vector<std::string> input; //vector of the file data
        public:
                CLASS(){}; //constructor
                void openfile(); //initialization of the openfile function
                bool readfile(); //initialization of the readfile function
                void count(); //initialization of the count function
                bool find();
};
#endif //end of header file and guards 


In CLASS.cpp:
1
2
3
4
bool CLASS::find(){
        cout << "class::find was called." << endl;
        return true;
}


In my mind, I believe this should work. It's pretty frustrating right now.

However, I'm getting this error:
1
2
3
STUDENT.cpp: In member function âbool student::find()â:
STUDENT.cpp:109:16: error: cannot call member function âbool CLASS::find()â without object
make: *** [STUDENT.o] Error 1
To call methods of a class you first need to create an instance of that class (a variable of type CLASS) and then call the method of that particulat instance

1
2
3
4
if (option == "3"){
     CLASS instance;
     instance.find();
}


That way of calling methods (classname::function) applies only to static functions (or static variables). If you did

1
2
3
4
5
6
7
8
9
10
class CLASS { //starts the CLASS class
        private:        //private section for variables the user does not need access to
                std::vector<std::string> input; //vector of the file data
        public:
                CLASS(){}; //constructor
                void openfile(); //initialization of the openfile function
                bool readfile(); //initialization of the readfile function
                void count(); //initialization of the count function
                static bool find();
};


Then a call to CLASS::find() would follow the correct syntax of calling a static method
As the compiler says, you cannot call a member function of a class without creating an object of that class first. Otherwise the function should be declared as static in the class.
Ah! I figured I forgot something! Thank you!
Topic archived. No new replies allowed.