sigalor
sigalor

Reputation: 1369

Do not use class member function inside class

I want to write an object-oriented wrapper around old C-style functions, while keeping the actual function names the same. Take a look at an example:

#include <iostream>

void doStuff(int a, float b)
{
    std::cout << "a = " << a << ", b = " << b << "\n";
}

class Stuff
{
    private:
        int a;
        float b;

    public:
        Stuff(int newA, float newB) : a(newA), b(newB) { }

        int getA() { return a; }
        float getB() { return b; }
};

class Widget
{
    public:
        void doStuff(Stuff s)
        {
            doStuff(s.getA(), s.getB());            //error: no matching function for call to 'Widget::doStuff(int, float)'
        }
};

int main()
{
    Widget w;

    w.doStuff(Stuff(42, 3.14f));

    return 0;
}

In this example, void doStuff(int a, float b) is the old C-function. Because in my real code, its equivalent is in an external library/header file, I cannot change its name. Next, Stuff is a container for keeping the values void doStuff(int a, float b) needs. The important things happen in Widget: void Widget::doStuff(Stuff s) should be the actual wrapper. I now expect doStuff(s.getA(), s.getB()) to call the old C-style function void doStuff(int a, int b) but the compilation fails with the given error.

Is it possible to make this code work without changing the name of the both doStuff functions? One option I already thought of is surrounding void doStuff(int a, float b) by some namespace. This works, but seems like very bad practice to me.

My compiler is mingw-w64 with g++ 5.2.0, so C++11 and C++14 are available.

Upvotes: 0

Views: 55

Answers (2)

Rakete1111
Rakete1111

Reputation: 48958

The doStuff(Stuff s) method in your class hides the global function doStuff(int a, float b). If you want to call the global doStuff function, you have to use the scope resolution operator :: (::doStuff(s.getA(), s.getB());)

Upvotes: 4

Steve
Steve

Reputation: 1810

Try making your call like this:

::doStuff(s.getA(), s.getB());

Upvotes: 0

Related Questions