tags:

views:

162

answers:

4

Here's my class definition:

class A {
    public:
        void do_lengthy_work() {
        cout << "working." << endl;
        }
};

I have an object of type A, and I want to call do_lengthy_work() on it:

A a;
a.do_lengthy_work();

Is it also possible to call the same method using some variant of the following?

A::do_lengthy_work(a);
+2  A: 

Yes, if the method is declared to be static, meaning it does not belong to a particular instance of the class.

class A {
    public:
    static void do_lengthy_work() {
        cout << "working." << endl;
    }
};

A::do_lengthy_work();
Jeff L
+2  A: 

You could do this.

static void do_lengthy_work(A& a) {
    a.do_lengthy_work();
}
Daniel A. White
+2  A: 

The way you wrote it, no you can't do that. You could create a static overload, although I would advise against this:

class A {
    public:
        void do_lengthy_work() {
        cout << "working." << endl;
        }

        static void do_lengthy_work(A& a) {
            a.do_lengthy_work();
        }
};

However, this can be confusing. Why do you want to do this? Why can't you just call a.do_lengthy_work()?

Adam Rosenfield
Just curious, because this is something that can be done in Python.
Goose Bumper
+12  A: 

You can wrap the function with mem_fun_ref:

mem_fun_ref(&A::do_lengthy_work)(a);

This can be very useful for STL algorithms like for_each:

std::vector<A> vec;
std::for_each(vec.begin(), vec.end(), mem_fun_ref(&A::do_lengthy_work));

If you have an A *, you would use mem_fun:

std::vector<A *> vecp;
std:for_each(vecp.begin(), vecp.end(), mem_fun(&A::do_lengthy_work));
R Samuel Klatchko