Ошибка reference to non static member function must be called

I’m using C++ (not C++11). I need to make a pointer to a function inside a class. I try to do following:

void MyClass::buttonClickedEvent( int buttonId ) {
    // I need to have an access to all members of MyClass's class
}

void MyClass::setEvent() {

    void ( *func ) ( int ); 
    func = buttonClickedEvent; // <-- Reference to non static member function must be called

}

setEvent();

But there’s an error: «Reference to non static member function must be called». What should I do to make a pointer to a member of MyClass?

imreal's user avatar

imreal

10.2k2 gold badges32 silver badges48 bronze badges

asked Oct 13, 2014 at 1:04

JavaRunner's user avatar

2

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

answered Oct 13, 2014 at 1:34

imreal's user avatar

imrealimreal

10.2k2 gold badges32 silver badges48 bronze badges

1

you only need to add parentheses after the function call and pass arguments if needed

answered Jan 28 at 22:00

téma el bouaazzaoui's user avatar

1

The reference to non-static member function must be called an error when developers include incorrectly converted members. As a result, the special member functions cannot initiate the tasks and commands, blocking the program from carrying out its primary purposes.reference to non static member function must be called

In addition, developers and programmers refer to the static member functions as pure virtual functions because they are not visible in the program but carry critical commands.

So, this article is the finest guide to fixing the non-static data member error from your document or program without affecting secondary functions.

Contents

  • Why Is the Reference to Non-static Member Function Must Be Called Error Happening?
    • – Including Pointers in C++ Without Adequate Values
    • – The Compare Function Is Not Static
    • – Encapsulating a Project Into a Class Definition
  • How To Fix the Reference to Non-static Member Function Must Be Called?
    • – Make the Listen Function Static
  • Conclusion

Why Is the Reference to Non-static Member Function Must Be Called Error Happening?

This C++ non-static function error happens when developers and programmers remove the pointer from a non-static method of a class. As a result, the program does not recognize the functions because the values and elements are incorrect, causing the error message to be displayed.

Although this is not a challenging error for experienced users, beginners and novice developers might struggle, especially when working on complex files. Still, our experts are confident you will not experience significant drawbacks and obstacles to fixing the error.

In addition, this error might happen due to incorrect members inside a C++ function because tags must point to a member to invoke the method. Consequently, the program responds to the false values and displays the error syntax.

However, developers should not worry because this bug does not affect other functions and elements vital during prolonged programming sessions. Therefore, debugging this error will not ruin your file, although we recommend double-checking the secondary commands and tags.

On the flip side, our experts believe learning about the error syntax is sometimes more important than debugging the code. As a result, this article has several chapters providing incorrect syntaxes using common examples and principles. Furthermore, we will teach you how to solve the error after you finish reading the following chapter.

– Including Pointers in C++ Without Adequate Values

Developers and programmers sometimes include pointers in C++ without good values, causing the error to appear and obliterate your user experience. For instance, pointing to a function inside a class is sometimes vital for complex documents because it introduces advanced operations.

However, the clicked event inside the syntax does not indicate a member invoking it. Therefore, C++ does not render the command promptly, displaying a total error message.

The following example points to a function in class incorrectly:

void MyClass::buttonClickedEvent( int buttonId ) {

// I need to have an access to all members of MyClass’s class

}

void MyClass::setEvent() {

void ( *func ) ( int );

func = buttonClickedEvent; // <– Reference to non-static command must be called

}

setEvent();

As you can tell, the operations and members are straightforward, but the program causes the error with severe consequences to your file.

In addition, this syntax may appear correct and functional to an inexperienced developer, the error is obvious, and programmers can quickly fix it. Still, not knowing what the error is causes inconveniences and difficulties. However, the error can happen due to other typical mistakes.

– The Compare Function Is Not Static

Your document can have many commands, but the compare function can cause the error unless it is static. For instance, the values and elements may have correct inputs, but it is all in vain if the compare function is not fixed, which is essential when creating complex C++ commands.

In addition, the other prompts are not critical because the program renders their operations correctly, helping developers debug the error.Reference to Non static Member Function Must Be Called Causes

This example includes the compare function without a static trait:

class Solution {

public:

bool Compare(int a, int b){

if(a%2==0 && b%2!=0)

return true;

else

return false;

}

vector<int> sortArrayByParity(vector<int>& A) {

sort(A.begin(),A.end(),Compare);

return A;

}

};

Nothing appears wrong or unfunctional, but the program displays the error and its total message. As a result, developers can’t complete the project unless they remove the error. Still, the solution is not complicated, but more on this in this article’s later chapters.

– Encapsulating a Project Into a Class Definition

Developers reported the same bug when encapsulating projects into class definitions with separate processing threads. Although this operation renders the commands correctly, further issues appear when programmers try to translate the project into a class definition.

As a result, the same bug appears, pointing to the callback function inside the auxiliary task and the specific coordinates. In addition, this example consists of two syntaxes introducing different commands.

First, this example introduces the class.h command:

private:

AuxiliaryTask sourceAnalysis_;

void source_analysis_routine(void *);

The auxiliary task includes source analysis, followed by the void command, which is critical for the file’s subsequence operation. Furthermore, developers must include the class.cpp command that introduces the primary and secondary functions for the same project.

Again, the syntax should not be complicated to comprehend, but we recommend reading the parts carefully.

Use the class.cpp command to introduce the following functions:

sourceAnalysis_ = Bela_createAuxiliaryTask(source_analysis_routine, 70, “bela-source-analysis”);

void Class::source_analysis_routine(void *)

{

// placeholder function (I don’t think this is where my problem is, although I am calling another command from here)

aVariable_ = true;

anotherFunction(true, false, cachedValue_);

}

The methods and commands in this code appear normal and functional, but unfortunately, the developers removed the non-static definition of a class. As a result, the program displays an annoying error and affects your schedule, but our solutions are here to help you.

Developers and programmers must include a pointer to a member to invoke the command, debug the error, and enable your program’s primary functions. Although the solution methods have similar syntaxes, your program can react differently, so we recommend double-checking the members with non-static traits.

Therefore, developers will understand where to invoke the command without severe drawbacks on the other operations. In addition, the method will pass a callback to the auxiliary task.

Learn how to fix the error by looking at the following method:

class Class {

….

void source_analysis_routine();

static void source_analysis_routine_static(void* arg) {

Class* that = (Class*)arg;

that->source_analysis_routine();

}

};

//…

sourceAnalysis_ = Bela_createAuxiliaryTask(Class::source_analysis_routine_static, 70, “bela-source-analysis”, (void*)this);

This syntax states the method has a meaning in association with the object, so the method’s address cannot be implemented for something useful. In addition, the argument for the callback must be a pointer to an object so that the process can refer it back to a class with a non-static trait.

– Make the Listen Function Static

Our experts offer another solution if the previous method does not debug your program. Although this method follows the same principle, it affects other functions because developers must make the listen to process static.

As a result, the program removes the complete error message without damaging primary and secondary commands.Make the Listen Function Static

Refer to the following syntax to debug the error from your computer:

class _tcp {

uv_tcp_t* tcp = NULL;

public:

~_tcp() { delete tcp; }

static void listen_uv_listen_uv_connection_cb(uv_stream_t* stream, int status) {

printf(“NEW CONNECTIONn”);

}

void listen(const char* host, int port) {

tcp = new uv_tcp_t();

uv_tcp_init(uv_default_loop(), tcp);

sockaddr_in* addr = new sockaddr_in();

uv_ip4_addr(host, port, addr);

uv_tcp_bind(tcp, (const sockaddr*)addr, 0);

delete addr;

uv_listen((uv_stream_t*)tcp, TCP_BACKLOG,

&_tcp::listen_uv_listen_uv_connection_cb);

}

};

As you can see, our experts included a new parameter for the method, creating a complex command. In addition, programmers must assign a new pointer for the handle function:

void listen(const char* host, int port) {

tcp = new uv_tcp_t();

uv_tcp_init(uv_default_loop(), tcp);

tcp->data = this; // do not forget it

}

The values in your document can be longer or shorter, but this method is full-proof for all applications. Therefore, you will no longer experience these inconveniences.

Conclusion

The non-static handle function error affects C++ programs with inadequate values and elements, although it can affect other programs and syntaxes. On the flip side, this guide helped you understand the debugging solutions, but our experts also covered the following bullet points:

  • The C++ program cannot carry out the primary functions if the complete error message persists
  • The error usually affects members without static traits inside the syntax, although it can change other values
  • Your total error syntax can have different values and elements, but the solutions methods remain unchanged
  • Our experts recommend swapping the non-static traits with static prompts in your files
  • Referring to the second solution would be best if the primary syntax does not fix the error

Programming and developing complex functions is dynamic because the commands might include several bugs and errors. Although fixing a mistake is sometimes challenging, this guide answered all your questions and cleared your doubts regarding static commands.

  • Author
  • Recent Posts

Position is Everything

Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team

Position is Everything

  • Forum
  • Beginners
  • reference to non static member function?

reference to non static member function?

I’m testing out classes, and I’m confused on how to get past the error:
«reference to non-static member function must be called; did you mean to call it with no arguments?»

Dog.h

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#ifndef DOG_H_INCLUDED
#define DOG_H_INCLUDED
#include <iostream>

using namespace std;

class Dog
{
    public:
    typedef std::size_t size_type;
    static const size_type CAPACITY = 200;
    Dog() : used(0) {}
    string GetData(){return data[used];}

    void insert(const string entry);
    private:
        string data[CAPACITY];
        size_type used;

};


#endif // DOG_H_INCLUDED 

Dog.cpp

1
2
3
4
5
6
7
8
9
10
#include "Dog.h"



void Dog::insert(const string entry) {

    data[used] = entry;
    ++used;

}

main.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include "Dog.h"

using namespace std;

int main()
{
    cout << "Hello world!" << endl;
    Dog dog;
    dog.insert("pomeranian");
    cout << dog.GetData;
    return 0;
}

Tried «static void insert …» already?

Try posting the ENTIRE error message you get.

@FurryGuy

main.cpp|11|error: reference to non-static member function must be called; did you mean to call it with no arguments?|

In main.cpp line 11 should be cout << dog.GetData();

No, the ENTIRE error message your compiler is showing.

something like this:

1>6-4_AmbiguousStatements.cpp
1>6-4_AmbiguousStatements.cpp(18): error C2065: 'cout': undeclared identifier

is much more helpful to figuring out what is wrong than what you post.

cout << dog.GetData; should be cout << dog.GetData();

GetData() is a class member function, not a class variable.

Topic archived. No new replies allowed.

When sorting a container in C++ using the standard library’s std::sort function, it’s often desirable to use a custom comparison function to define the sort order. However, it’s common to encounter the error «reference to non-static member function must be called» when using a class member function as the comparison function. This error occurs because class member functions have a hidden this pointer, which must be passed when calling the function, but std::sort expects a plain function or function pointer. In this article, we’ll explore two methods for resolving this error and correctly using a custom comparison function with std::sort.

Method 1: Use a static member function or free function

To fix the error «reference to non-static member function must be called» when using a custom compare function with std::sort in C++, you can use a static member function or a free function instead of a non-static member function. Here is an example of how to use a static member function:

class MyClass {
public:
    static bool compare(const int& a, const int& b) {
        return a < b;
    }
};

int main() {
    std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};

    std::sort(vec.begin(), vec.end(), MyClass::compare);

    for (const auto& i : vec) {
        std::cout << i << ' ';
    }
    std::cout << 'n';

    return 0;
}

In this example, the compare function is declared as a static member function of the MyClass class. The std::sort function is then called with MyClass::compare as the compare function.

Here is an example of how to use a free function:

bool compare(const int& a, const int& b) {
    return a < b;
}

int main() {
    std::vector<int> vec = {3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5};

    std::sort(vec.begin(), vec.end(), compare);

    for (const auto& i : vec) {
        std::cout << i << ' ';
    }
    std::cout << 'n';

    return 0;
}

In this example, the compare function is declared as a free function outside of any class. The std::sort function is then called with compare as the compare function.

Either way, using a static member function or a free function allows you to use a custom compare function with std::sort without encountering the «reference to non-static member function must be called» error.

Method 2: Use a functor (object of a class with operator())

To fix the error «reference to non-static member function must be called» when using a custom compare function with std::sort in C++, you can use a functor (object of a class with operator()). Here’s how to do it:

  1. Define a class with operator() that takes two arguments and returns a bool:
class MyCompare {
public:
    bool operator()(const MyClass& a, const MyClass& b) const {
        return a.someMember < b.someMember;
    }
};
  1. Instantiate an object of the class:
  1. Pass the object to std::sort as the third argument:
std::sort(myVector.begin(), myVector.end(), myComp);

Here’s a complete example:

#include <algorithm>
#include <vector>

class MyClass {
public:
    int someMember;
};

class MyCompare {
public:
    bool operator()(const MyClass& a, const MyClass& b) const {
        return a.someMember < b.someMember;
    }
};

int main() {
    std::vector<MyClass> myVector;
    MyCompare myComp;

    // populate myVector with some MyClass objects

    std::sort(myVector.begin(), myVector.end(), myComp);

    // do something with the sorted vector
}

yaoman

0 / 0 / 0

Регистрация: 24.03.2015

Сообщений: 11

1

24.03.2015, 17:10. Показов 11698. Ответов 8

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Здравствуйте. Помогите, пожалуйста, с проблемой : не могу вызвать метод из QMap.

mainwindiw.h:

C++ (Qt)
1
2
3
4
5
6
7
8
class MainWindow : public QMainWindow
{
    Q_OBJECT
 
public:
 
    void setText();
}

mainwindow.cpp:

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
void MainWindow::setText() {
    ui->plainTextEdit->appendPlainText("Hello world!");
}
 
void MainWindow::on_pushButton_3_clicked()
{
    QMap <QString, void(*)()> mFunctions;
    mFunctions["setText"] = setText;
    mFunctions["setText"]();
}

Ошибки :

mainwindow.cpp:327: ошибка: reference to non-static member function must be called; did you mean to call it with no arguments?
mFunctions[«setText»] = setText;
^~~~~~~
()
mainwindow.cpp:327: ошибка: assigning to ‘void (*)()’ from incompatible type ‘void’
mFunctions[«setText»] = setText;
^ ~~~~~~~

Пытался заменить void(*)() множеством способов, но все равно выводит ошибки.
Расскажите, пожалуйста, работающий метод вызова функции по тексту в QT. Спасибо.



0



dzrkot

zzzZZZ…

527 / 358 / 94

Регистрация: 11.09.2013

Сообщений: 2,041

24.03.2015, 17:57

2

вот так будет работать, проблема будет если foo будет являться методом класса. Т.е. можно по идее просто сделать friend функции

C++ (Qt)
1
2
3
4
5
6
7
8
9
10
11
void foo()
    {
    qDebug()<<"foo";
    }
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
QMap <QString, void(*)()> mFunctions;
mFunctions["setText"] = foo;
mFunctions["setText"]();
}

ну или вот так, но как вызвать функция я не знаю сам

C++ (Qt)
1
2
3
4
5
6
7
Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
QMap <QString, void(Widget::*)()> mFunctions;
mFunctions["setText"] = foo;
mFunctions["setText"]();
}



0



0 / 0 / 0

Регистрация: 24.03.2015

Сообщений: 11

24.03.2015, 18:08

 [ТС]

3

К сожалению ваш способ не работает.



0



Croessmah

Неэпический

17819 / 10592 / 2044

Регистрация: 27.09.2012

Сообщений: 26,636

Записей в блоге: 1

24.03.2015, 18:28

4

C++
1
2
3
4
QMap < int , std::function<void()> > mFunctions ;
 
mFunctions["setText"] = std::bind (&MainWindow::setText , *this) ;
mFunctions["setText"]();



0



0 / 0 / 0

Регистрация: 24.03.2015

Сообщений: 11

24.03.2015, 18:48

 [ТС]

5

В ключе QMap необходимо QString, а не int.
на bind выдает ошибку.
Попытался вызвать иные функции, предложенные IDE с bind. Так же ошибки.
Предложите, пожалуйста, иной работающий способ на QT.



0



MakeEasy

41 / 41 / 26

Регистрация: 24.02.2015

Сообщений: 151

24.03.2015, 19:21

6

Цитата
Сообщение от dzrkot
Посмотреть сообщение

ну или вот так, но как вызвать функция я не знаю сам

Вот так :

C++
1
2
3
4
5
    MainWindow mainWindow1;
    (mainWindow1.*(mFunctions["setText"]))();
    
    MainWindow *mainWindow2;
    (mainWindow2->*(mFunctions["setText"]))();



1



0 / 0 / 0

Регистрация: 24.03.2015

Сообщений: 11

24.03.2015, 19:29

 [ТС]

7

Ошбики(



0



MakeEasy

41 / 41 / 26

Регистрация: 24.02.2015

Сообщений: 151

24.03.2015, 19:34

8

Лучший ответ Сообщение было отмечено yaoman как решение

Решение

Вот так ошибка?

C++
1
2
3
4
5
6
void MainWindow::on_pushButton_3_clicked()
{
    QMap <QString, void(MainWindow::*)()> mFunctions;
    mFunctions["setText"] = &MainWindow::setText;
    (this->*(mFunctions["setText"]))();
}



2



0 / 0 / 0

Регистрация: 24.03.2015

Сообщений: 11

24.03.2015, 20:45

 [ТС]

9

Спасибо огромное!



0



  • Ошибка rfc iveco stralis
  • Ошибка ret s 04017 00
  • Ошибка resume from hibernation
  • Ошибка restart your computer
  • Ошибка restart replace movefileex сбой код 5