Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error - cannot call member function without object in C++

Tags:

c++

class

I get the compile error

cannot call member function ‘bool GMLwriter::write(const char*, MyList<User*>&, std::vector<std::basic_string<char> >)’ without object

when I try to compile

 class GMLwriter{
    public:
    bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
};

the function is defined later and called in main with

GMLwriter::write(argv[3], Users, edges);

Users is declared before with MyList<User*> Users; (MyList is a List ADT and I have a User class) and edges is declared with vector<string>edges

to what object is this error referring?

like image 329
user2059901 Avatar asked Feb 11 '13 04:02

user2059901


2 Answers

GMLwriter::write is not static function of GMLwriter, you need to call it through object. For example:

GMLwriter gml_writer;   
gml_writer.write(argv[3], Users, edges);

If GMLwriter::write doesn't depend on any GMLwriter state(access any member of GMLwriter), you can make it a static member function. Then you could call it directly without object:

class GMLwriter
{
public:
   static bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
   ^^^^
};

then you could call:

GMLwriter::write(argv[3], Users, edges);
like image 196
billz Avatar answered Oct 04 '22 20:10

billz


GMLwriter is not an object, it's a class type.

Calling member functions requires an object instance, ie:

GMLwriter foo;   
foo.write(argv[3], Users, edges);

Although there's a good chance you intended the function to be free or static:

class GMLwriter{
    public:
    // static member functions don't use an object of the class,
    // they are just free functions inside the class scope
    static bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
};

// ...
GMLwriter::write(argv[3], Users, edges);

or

bool write(const char *fn, MyList<User*>& my_vec, vector<string>edges);
// ...
write(argv[3], Users, edges);
like image 37
Pubby Avatar answered Oct 04 '22 20:10

Pubby