0

I have 3 files pos.h pos.cpp and main.cpp .... I am trying to call a function from pos.cpp in the main class for instance :

pos.h file

class pos {
   public:
   pos(); //defualut constructor 
int open_port();
}

pos.cpp

#include "pos.h"
int Open_port()    {
//do stuff here
    return 0;
    }

class main.cpp

#include "pos.h"
int main(int argc , char** argv) {
pos pos1;
pos1::Open_port();
}

Problem is I always get that pos1 is not a class or namespace I am compining as follows g++ mainpos.cpp pos.cpp pos.h -o position -lpthread Any thoughts ?

Zeyad
  • 771
  • 3
  • 9
  • 14
  • 1
    You want `pos1.open_port();` instead of accessing it via :: in your `main` function. And in pos.cpp, you need `pos::open_port` as the function name, not `Open_port` (case matters) – Mark Ormston Jun 18 '13 at 19:40

3 Answers3

2

You seems to have several issues in the code:

int open_port();

is a member function of pos. However, when you define it, you are not using :: operator and the function name is changed.

Try:

 int pos::open_port()
 {      ///^^pay attention to typos
     //do stuff here
     return 0;
 }

Then inside main. you can do:

 pos pos1;
 pos1.open_port();

If you really mean Open_port(), which is not a member of the class, then you need to add function declaration into the proper header files and use it properly, but that's a separate issue.

taocp
  • 23,276
  • 10
  • 49
  • 62
0

You've several problems, most of them related to fundamental syntax:

  1. Case matters. open_port and Open_port are two completely different things

  2. You're not actually defining the method of the class pos, you're making a new function

    int Open_port()    {
    

    needs to be

    int pos::open_port()    {
    
  3. You're trying to invoke a non-static method statically. You need to create an instance of pos, (which you've done, pos1) and invoke open_port on it via pos1.open_port(). You cannot call pos::open_port directly, unless you declare the method static.

  4. A final problem would be that you've declared but not defined the default constructor for your class. You need to provide a method body for pos::pos().

user229044
  • 232,980
  • 40
  • 330
  • 338
0

Well, you have two problems with your code. In the cpp file you need to use the scope for that function, so you need to have:

int pos::Open_port()

Also, you need to ensure that open_port and Open_port are spelled and capitalized the same.

Last thing, if you want to call open_port like that, you'll need to decare the function as static in the class def'n.

Tyler Jandreau
  • 4,245
  • 1
  • 22
  • 47