Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is a function kind of like a static method?

I'm a java programmer and am trying to understand the difference between a method (java methods) and a function (such as in c++). I used to think that they are the same, just different naming conventions for different programming languages. But now that I know they are not, I am having trouble understanding the difference.

I know that a method relates to an instance of a class and has access to class data (member variables), while a function does not (?). So is a function kind of like a static method?

See here for explanations I read which led me to think this.

like image 458
lkm Avatar asked May 07 '10 02:05

lkm


2 Answers

A function is simply a generic name for a portion of code within a program. The word "method" is a synonym for function. So are "subroutines" and "procedures," etc.

Java and C++ functions are for the most part exactly the same thing.

The word "method" tends to be used for subroutines associated with an instance, while "function" tends to be used for those that are global/static.

But even then, "methods" are generated by the compiler as though they were "functions."

Consider this C++ code:

class Foo
{
public:
    void DoFoo(int param)
    {
        printf("%d, %d\n", param, member);
    }
private:
    int member;
};

int main()
{
    Foo f;
    f.DoFoo(42);
    return 0;
}

The compiler generates code to something equivalent to this:

struct Foo
{
    int member;
};

void Foo_DoFoo(Foo* this, int param)
{
    printf("%d, %d\n", param, this->member);
}

int main()
{
    Foo f;
    Foo_DoFoo(&f, 42);
    return 0;
}

So the distinction between "method" and "function" is merely a convention.

like image 88
In silico Avatar answered Oct 02 '22 02:10

In silico


This is strictly a vocabulary difference. Some consider a method an operation that belongs to an object or a class, and a function an operation that doesn't. Others, like the C++ crowd, call them both functions but refer to free functions or non-member functions when the function doesn't belong to a class or an object. I personally use the two interchangeably.

All in all, in the C++ jargon when you wish to refer to specific kinds of functions (non-members, members, returning no value, ...) you add an adjective to the noun function: a friend function, a void function, a member function and so on.

like image 30
wilhelmtell Avatar answered Oct 02 '22 02:10

wilhelmtell