LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Understanding Class Member Functions (http://www.linuxquestions.org/questions/programming-9/understanding-class-member-functions-4175467477/)

Ace Blackwell 06-26-2013 11:52 AM

Understanding Class Member Functions
 
All,

I have a programming question about classes. Iím reading and re-reading about them. I understand the general idea, not claiming to know all there is to know, hence this question.

Iím not seeing the vast benefit to the member functions. Unless they do some level of automated activities, such as a constructor , what is the difference between member functions and normal functions isolated to their own file? It appears that you still have to call the function separate to get them to do anything, and if you include any files with your program to allow you to use the member functions, then they arenít any more transparent than any other function.

Iím not trying to argue against member function or question their usefulness. But without seeing any unique benefit I feel that Iím just not understanding the true concept of them. Just trying to get a little education. LOL

Ace

Doc CPU 06-26-2013 12:21 PM

Hi there,

Quote:

Originally Posted by Ace Blackwell (Post 4979066)
I have a programming question about classes. I'm reading and re-reading about them. I understand the general idea, not claiming to know all there is to know, hence this question.

I'm not seeing the vast benefit to the member functions. Unless they do some level of automated activities, such as a constructor, what is the difference between member functions and normal functions isolated to their own file?

I'm not sure what you mean by the term "member functions", but I guess you mean the set of functions tied to a class. Usually these are called methods, so let's use this more common term.

Well, the advantage of methods over standalone functions is that the calling syntax is more intuitive than with ordinary functions, as this example in C++ pseudo syntax is meant to illustrate:

Code:

// call a method of a class on a particular object of that class:
anyobject.dosomething(more args);

// corresponding call using ordinary functions:
dosomething(&anystruct, more args);

The point is that methods of a class usually don't work independently; rather, they work on an object of that class. To achieve that in traditional C, you have to pass that function a pointer to a struct holding the data; in C++, however, this pointer is passed automatically as a hidden argument which is addressable as 'this' inside the method. AFAIK 'this' is even the default scope inside a method, so that you can access any member variables directly (without using this->var), and this access is automatically tied to the object (instance) on which the method was called.

Quote:

Originally Posted by Ace Blackwell (Post 4979066)
It appears that you still have to call the function separate to get them to do anything

Yes, of course you have. Calling functions in the right order and in the right context is an inevitable part of the program's logic. The trick is really just this implicit link between the code and the data object it is working with.
Actually, I also favor the traditional non-class style; in programming, I'm in for explicitness instead of hidden magic - even if that means a bit more typing.

[X] Doc CPU

johnsfine 06-26-2013 01:13 PM

Quote:

Originally Posted by Ace Blackwell (Post 4979066)
what is the difference between member functions and normal functions

The key difference is that inside the definition of the member function, the other members of the specified object are in scope.

Consider these two styles of programming:
Code:

void bump( myClass &thing ) {
  thing.x += thing.y * thing.z; }

vs.
Code:

void myClass::bump() {
  x += y * z; }

I'm obviously assuming x, y and z are data members of myClass.

Obviously either style can get the job done. But from experience I am confident that in real projects the second style leads to more readable and maintainable code.

With the second style, you also have the option to protect members of the class for better "encapsulation". I personally think that feature of C++ is over used and too much encapsulation does as much harm as too little. But anyway you get the choice.
Quote:

Originally Posted by Doc CPU (Post 4979080)
I'm not sure what you mean by the term "member functions",

It is a common enough term and I think you did understand it.

Quote:

the calling syntax is more intuitive than with ordinary functions, as this example in C++ pseudo syntax is meant to illustrate:

Code:

// call a method of a class on a particular object of that class:
anyobject.dosomething(more args);

// corresponding call using ordinary functions:
dosomething(&anystruct, more args);


I think it is quite debatable whether object.function() is more intuitive than function(object). If that & I marked in your example is the reason it is less intuitive, simply declare the function to take a reference rather than a pointer.

I'm used to object.function() rather than function(object) because I have been programming C++ a long time, but being used to something doesn't mean it was really more intuitive.

I think the syntax object.function is only better (as a matter of language design) because when calling another member inside a member function, you can (usually) leave out the first part of (*this).another() and simply write another(). The overloading would be too unwieldy if the hidden this parameter used normal parameter syntax when explicit.

Quote:

AFAIK 'this' is even the default scope inside a method, so that you can access any member variables directly (without using this->var), and this access is automatically tied to the object (instance) on which the method was called.
Right. In my opinion, that is the fundamental feature around which this part of the language is designed, rather than being (as you seem to describe it) just another detail.

Sergei Steshenko 06-26-2013 02:17 PM

In addition to what others have already said.

You may consider class data members as locally global variables - yes, I know it sounds like an oxymoron.

They are global in the sense they are seen by class member function similar to the way a regular global variables are seen by a regular "C" functions.

Still, the variables are local in the sense they are seen only inside the class.

But from linker point of view class data members are in no way static/global - opposed to "C" global variables.

Doc CPU 06-26-2013 04:31 PM

Hi there,

Quote:

Originally Posted by johnsfine (Post 4979103)
Quote:

Originally Posted by Doc CPU (Post 4979080)
I'm not sure what you mean by the term "member functions", but I guess you mean the set of functions tied to a class. Usually these are called methods, so let's use this more common term.

It is a common enough term and I think you did understand it.

I did, indeed, only I wasn't sure whether I'd got it right.

Quote:

Originally Posted by johnsfine (Post 4979103)
I think it is quite debatable whether object.function() is more intuitive than function(object).

That's what I tried to express with my remark about explicitness further down.

Quote:

Originally Posted by johnsfine (Post 4979103)
If that & I marked in your example is the reason it is less intuitive, simply declare the function to take a reference rather than a pointer.

A reference and a pointer are just two different words for exactly the same thing - but "reference" is a term unknown in plain C. And even though I may be repeating myself: No, I'm not used to the "advantages" of C++. I can use C++ when I'm forced to, but I rather prefer plain C.

[X] Doc CPU

JohnGraham 06-26-2013 05:03 PM

Quote:

Originally Posted by Ace Blackwell (Post 4979066)
I’m not seeing the vast benefit to the member functions. Unless they do some level of automated activities

This is a good question - you should always ask about things you're unsure of.

The real benefit isn't really from member functions themselves, it's from the encapsulation you get from having private member variables. For example, in the class:

Code:

class Object {
public:
  int var_public;

private:
  int var_private;

public:
  void function();
};

Here Object::var_private is only accessible from within the class - you can make changes to it without worrying about breaking code in other classes, since in this case only Object::function() can access it. So long as Object::function() uses Object::var_private correctly, anyone using the class will see the correct behaviour. On the other hand, if you want to change what Object::var_public does then you have to worry about users of the class. This can be a particular worry if you're writing a library, where you don't know who's using your classes, or how.

So the real benefit is in knowing that member functions - and only member functions - have access to their class's private data.

(This ignores that a class may have friend functions/classes, which just muddies the waters a bit - the point is still the same.)

ta0kira 06-26-2013 08:13 PM

In addition to the comments above, when using virtual functions the object itself contains a pointer to a table containing the version of the function applicable to that object. E.g.
Code:

#include <iostream>


struct base
{
    virtual void func() const
    { std::cerr << "base\n"; }

    virtual ~base() {}
};

struct derived : base
{
    virtual void func() const
    { std::cerr << "derived\n"; }
};


static void i_need_a_base_for_some_reason(const base &val)
{
    std::cerr << "something\n";
    val.func();
    std::cerr << "something else\n";
}


int main(int argc, char *argv[])
{
    base b;
    derived d;

    i_need_a_base_for_some_reason((argc % 2)? b : d);
}

The program above will execute a different member function depending on the command-line arguments. The member function that gets called in i_need_a_base_for_some_reason isn't known at compile time, yet it's still expressed as a single function call.

Kevin Barry

sundialsvcs 06-26-2013 08:28 PM

You don't use these very often, but when you do, they come in very handy.

Basically, a "class function" is a subroutine that isn't associated with "any particular instance of" an object within that class. (In other words, the notion of self simply isn't useful or relevant to what you have in mind for this function to do: this bit of code is associated with the class itself, not an instance. Nevertheless, it is associated with the class, e.g. in the sense that it should be able to see and to refer to things that are "private to the class," that is to say, "concealed from everyone-else.")

Sometimes, in the real world of programming, it's that notion of concealment that you really want to take advantage of. Within the understood boundaries of the class, you can define variables, constants, and functions that, well, that "live happily within their own little rubber-room," visible to one another, but not visible to anyone else unless you expressly want them to be. Given that a real-world application can easily consist of hundreds if not thousands of source-modules, this language-enforced capacity for concealment and isolation can be tremendously useful.

In the real world, "the language won't let you ..." really means this: "if you, without meaning to do this, actually try to do this, the language will catch your mistake at compile time." Priceless.

ta0kira 06-26-2013 08:35 PM

Quote:

Originally Posted by sundialsvcs (Post 4979290)
In the real world, "the language won't let you ..." really means this: "if you, without meaning to do this, actually try to do this, the language will catch your mistake at compile time." Priceless.

I had a terrible time as a result of this when I started getting into dynamically-typed interpreted languages. Getting errors up front can really save you a lot of time.

Ace Blackwell 06-27-2013 10:16 AM

All,

Thanks for the insight and education.

Doc, I debated on including the term Method given my information source is a few years old I didn't know if member function was still used.

I am far from adept where classes and their functions are concerned but feel like I do have a grasp on the concept. I can see some benefits to member functions but I personally am not convinced it worth forcing for the beginner/intermediate level coding I do for personal entertainment .

Thanks again ppl.

Ace

sundialsvcs 06-27-2013 10:29 AM

Quote:

Originally Posted by ta0kira (Post 4979295)
I had a terrible time as a result of this when I started getting into dynamically-typed interpreted languages. Getting errors up front can really save you a lot of time.

Yes, indeed. It was a real eye-opener how much time I had been wasting, writing JavaScript by hand and debugging it in a browser, when I stumbled-upon haXe, which is a cross-platform language that can, among other things, generate JavaScript output. It is a strongly-typed language, and that makes a world of difference. I now use it to write all of my JavaScript.

ta0kira 06-27-2013 10:43 AM

Quote:

Originally Posted by Ace Blackwell (Post 4979604)
Doc, I debated on including the term Method given my information source is a few years old I didn't know if member function was still used.

"Method" is the proper term in Java, and "function" is the proper term in C++. "Member" generally means a function that must be applied to an instance, and "class" and "static" generally mean a function that resides in the namespace of a class but might not require an instance. Then you have multimethods in e.g. Common Lisp, which is like a member function that's applied to multiple objects. It's all very complicated.

Kevin Barry

psionl0 07-01-2013 07:48 AM

OOP languages like C++ really come into their own when you are dealing with large programming projects written by more than one programmer.

The inheritance aspect means that you don't have to reinvent (or copy) the wheel. You can find a class that does substantially what you want it to do then extend it yourself to correct any lack. A software vendor doesn't even need to make the source code available for the base class - just the header and object files (plus suitable documentation of course ;)).

Encapsulation is the biggie when it comes to teamwork. By declaring variables and methods private, you can prevent others using them in ways in which you didn't intend and keep your options open for the future. For example, if a Date class has a private method called setMonth(), since nobody else can call it, you don't have to lock the method into a certain set of procedures. You don't even have to keep the parameters or return type the same. In fact, if you find a more efficient algorithm, you might even do away with the setMonth() method altogether and none of this will have any effect on the programmers who use your class.

Sergei Steshenko 07-01-2013 08:04 AM

Quote:

Originally Posted by psionl0 (Post 4981662)
...
The inheritance aspect means that you don't have to reinvent (or copy) the wheel. You can find a class that does substantially what you want it to do then extend it yourself to correct any lack. A software vendor doesn't even need to make the source code available for the base class - just the header and object files (plus suitable documentation of course ;)).
...

To be fair, the same can be done in "C" - luckily, DLLs (I am not talking specifically about Windows) exist as concept and implementation.

ta0kira 07-01-2013 08:27 AM

Quote:

Originally Posted by Sergei Steshenko (Post 4981666)
To be fair, the same can be done in "C" - luckily, DLLs (I am not talking specifically about Windows) exist as concept and implementation.

Good point. In fact, you can even change the underlying language while keeping the API the same.

Kevin Barry


All times are GMT -5. The time now is 09:44 PM.