iago-lito
iago-lito

Reputation: 3218

What's left for non-static functions c++?

There's something weird happening in my code these days. Each time I have to built a new member function, or each time I come back to a previously defined member function, I think:

"hey, this is gonna be the exact same process no matter which instance of this class is calling it, so let's make it static!"

and I also feel like it'll be less memory-consuming since each instance won't have to "carry" one implementation of the function, is that correct?

So instead of having things like:

class Foo
{
    int _attributes;

    double methods(int parameters)
    {
        // do stuff using..
    _attributes;

    };
};

I end up with things like:

class Foo
{
    int _attributes;

    static double methods(int parameters, Foo* instance)
    {
        // do stuff using..
    instance->_attributes;

    };
};

And I can't see any function that wouldn't be transformed this way anymore. All my functions are turning to static and I feel like there's something wrong somewhere..

What am I missing? What is the use of having non-static methods, again? XD

Upvotes: 1

Views: 114

Answers (2)

Gabe Sechan
Gabe Sechan

Reputation: 93708

Congratulations- you've recreated C object oriented programming. This is exactly how we did OOP in C. In fact, its how C++ does it too. it adds a parameter to every function named this which is pushed with the rest of the parameters. You're doing the same thing explicitly.

Why would you use member functions instead? Readability. myInstance.foo() is a lot more readable than myClass::foo(all, my, parameters, myInstance)

Upvotes: 6

merlin2011
merlin2011

Reputation: 75629

When you invoke a non-static function.

Foo foo;
foo.doSomething(ArgType arg1, ArgType2 arg2,...);

This compiles down to.

Foo foo;
doSomething(&foo, ArgType arg1, ArgType2 arg2,...);

I answered a similar question here about Java, but it is the same idea in both languages.

Upvotes: 4

Related Questions