Thread: built-in methods

  1. #1
    Registered User
    Join Date
    May 2009
    Posts
    242

    built-in methods

    As I learn C++, I've been keeping an Excel workbook to allow a summary of various aspects all in one worksheet. One of my worksheets is called "Methods," and I have some questions about the way I'm now structuring this. As background: I've been learning Java this fall and also want to understand structural similarities or differences between built-in methods in C++ and Java.

    In Java for sure, and I think in C++, there seem to be 3 kinds of built-in methods: constructors (example in C++: valarray<dataType>(), etc.), class instance methods, and class (?) static methods.

    Class instance methods in C++ are ones with prototypes like:

    void ignore(); for the class istream or
    void append(char * c) for the string class

    When you use them, they require a calling object (str.append("name")).

    Where I feel somewhat unsure is with what I'm calling static methods. I'm just not sure whether one should use that term in C++, but if not, then I don't know what to call them.

    Examples in C++ would be methods like

    int strlen(char * c); or
    void strcpy(char * c1, char * c2);

    In Java, examples would be something like

    int parseInteger(String s);

    But one big difference is that in Java, you then use the class name when you call the function (e.g., Integer.parseInteger("12")), whereas in C++ all you need to use is std:: as scope resolution operator (?).

    Anyhow, methods like strlen() or strcpy() are defined in header files, in this case <cstring>, but I'm guessing that the mechanics of the definition are somewhat different than the way in which Java just makes them static methods of some class.

    So, what would you call the method TYPE of these methods (that don't require a calling object) as opposed to the methods that do (where I don't see much problem calling those "instance methods" in C++, just as I've done in Java for methods requiring a calling object)?

    Or is the way in which this kind of method in C++ is defined in some library sufficiently similar to the definitions within classes in Java to warrant using the term "static methods" in C++, too?

  2. #2
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    strlen() or strcpy() are called "free functions". They are never called methods.

    The term method in C++ is a synonym for member functions, which means functions belonging to an object.

    Also, you forgot destructors, which are sortof but not quite analogous to finalizers in Java.

    You can have static methods (member functions) in C++ just like in java. They use the same key word. The big difference is instead of useing Integer.parseInteger("12") you would write Integer::parseInteger("12"). :: is the scope resolution opperator.

    std is a namespace, which is somewhat like a package in Java. To use something in the std namespace you have to either qualify the name with std:: (in Java it would be std.)or import the std namespace with the expression "using namespace std". In addition and unlike Java, you must include the header file in which the thing is spelled out (declared or defined depending on what king of thing it is). Alternatively in some cases you can provide your own definition/declaration.
    Last edited by King Mir; 12-20-2009 at 10:06 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  3. #3
    Registered User
    Join Date
    May 2009
    Posts
    242
    Thanks for the very helpful clarifications! A few follow-up questions, though:

    For purposes of a kind of C++ "vocabulary list" would you put the free functions on a completely different worksheet from the methods? The only structural difference I'm seeing is that the free functions don't belong to any class. They do, with the exception of constructors and destructors (good point), have a return type, signature and (except for fundamental functions/operators like =, ==, >, etc.) header.

    For rounding out the function/method types, you're definitely right that destructors also need to go on the list. At least as far as I've seen, you almost never use finalizers in Java, since it also has automatic garbage collection. And in C++, I don't think I've seen built-in destructors.

    On the static methods in C++, are there any of those that are built-in? If not, that may be a big difference. In any case, what is coming to mind for me are only user-defined static methods--and even then, I think I feel somewhat less prone to use them in C++ for whatever reasons ...

    The one thing I'm not so sure about in your comments is your correlation between namespaces in C++ and packages in Java. I'm more inclined to make a correlation between headers (can I call these "libraries"?) in C++ and packages in Java. I really thing the #include ... in C++ is more like the import ... in Java than the using declaration. Moreover, the packages are collections of files where the methods are defined, as are (or so is my impression) the libraries referenced in header files. My impression is that std and other namespaces don't actually specify prototypes for or "construct" anything but are rather a tool for keeping track of identifiers--and are something that I don't think Java has (and probably unnecessary, since all but the most basic identifiers are used only in conjunction with a class name anyway).

    As you noted, the "." in Java is overloaded to connect calling object to method (for instance methods) and scope resolution (for static methods like Integer.parseInteger()). But I think the :: operator in C++ is also overloaded so that on the one hand a class name goes on the left (MyClass::myMethod()) and on the other a namespace.

    Returning to an earlier issue that you mentioned, maybe I should also just generally prefer to use the term "function" in C++ (and "method" only for specific class methods), whereas Java seems to prefer using the term "method" for everything (probably also because everything is a class in Java).

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Aisthesis
    And in C++, I don't think I've seen built-in destructors.
    If a destructor is not defined but an object of the class needs to be destroyed, then the compiler will generate a destructor.

    Quote Originally Posted by Aisthesis
    On the static methods in C++, are there any of those that are built-in?
    What do you mean by "built-in"? Functions and classes are features of the core language, but the core language has no functions and classes built-in. Rather, you will find them in the standard library, other libraries, and your own code.

    Quote Originally Posted by Aisthesis
    I really thing the #include ... in C++ is more like the import ... in Java than the using declaration.
    Not really. The Java import keyword allows names to be used without package name qualification, e.g., import java.util.Scanner; allows you to use Scanner instead of java.util.Scanner. This is very similiar to how using std::cin; will allow you to use cin instead of std::cin.

    A C++ header contains forward declarations and any necessary class definitions (etc), and the #include effectively copies and pastes its contents into the translation unit, but there is nothing in Java that corresponds to a C++ header.

    By the way, in C++ specific parlance, method means virtual member function.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    May 2009
    Posts
    242
    By built-in, I mean that they're defined them without the user having to define them. Like the examples I gave: strlen, strcpy, append, ignore. I'm assuming that your point is that they're not part of the core language but defined in various libraries and hence (?) could also be hidden by a custom definition if you wanted to redefine std::strcpy.

    But, while they're not part of the core language, they're no doubt part of the current language specification. So, to be precise, rather than "built-in," (implying core language) I should have said "for which the language specification has standards."

    The java.util.Scanner thing was completely new to me. I thought you HAD to put the import in or it wouldn't find the object, but not true. I just took a simple program, commented out the import java.util.Scanner; at the top and then added java.util where I had just Scanner, and it worked. So, you're right.

    I guess what seems weird to me is that in C++ there's only one standard (i.e., part of the language standard) namespace that I've run across, namely std, whereas Java has you using several different packages pretty quickly.

    Also, you say:
    A C++ header contains forward declarations and any necessary class definitions (etc), and the #include effectively copies and pastes its contents into the translation unit, but there is nothing in Java that corresponds to a C++ header.
    and an important part of that is true for a Java package like java.util. Java doesn't to my knowledge have forward declarations, and the copy/paste part also doesn't apply (not sure what exactly Java does there, but I have seen elsewhere that an import costs little or nothing in terms of compiled file size).

    I don't know, I think I'm still of the opinion that Java packages are more like C++ libraries than like C++ namespaces. Or perhaps it's best to say that they're kind of between the two.

    I've been understanding a Java import statement as telling the compiler where to go to find definitions for the term in question; similarly the C++ #include but not the using, which doesn't tell the compiler anything about where to find the code defining the term in question. As I understand it (which of course may well be wrong), namespaces are just a tool for resolving potential naming conflicts in huge programs, and I don't think that's really the purpose of java packages, which are really more just libraries to use for various specialized tasks.

    As to the copy/paste aspect, which does seem to me to be a major difference, I suspect that that has more to do with the different ways that the compilers work in the two languages. It is true that if you say at the top in java:

    import java.util.*;

    and then don't use it or use only the Scanner object in that package, it costs you little or nothing. Of course, it does cost you something to use the Scanner object in the first place (as opposed to code that gets by without it), and that will presumably be the same whether you do import java.util.* or import java.util.Scanner or you don't even have an import but use the full term java.util.Scanner in your program.

    My impression is that there is a cost in C++ if you start throwing unnecessary includes into your program. I'm have to try just sticking #include <string> into a program that doesn't need it and see how that influences the size of the executable. I'm guessing it will have some noticeable influence.

  6. #6
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    C++ does indeed prefer the term function, and I don't think the term method is defined in the standard. However, when working in object oriented design then people generally talk about methods, not functions regardless of language, since design largely transcends language.

    The cost of extra includes is longer compilation time. There is no cost to the final running program. The compiled final program size should be the same.

    Overriding library functions will lead to linker errors, unless you use a different namespace. Functions and other things taken from C are defined in both the global namespace (basically without a namespace) and in std, while purely C++ librairy items are only in the std namespace (excepting macros, but that's another can of worms). But even then I would recommend avoiding using the same names as the standard libraries, unless there is no possibility of conflict when both namespaces are in scope.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  7. #7
    Registered User
    Join Date
    May 2009
    Posts
    242
    Agreed. I think it would be pretty poor programming to name a variable cin or a function strcpy in almost every situation--possible exception being if it's a logical extension of the usual usage but where you need some little extra nuance in the particular situation you're in, but even then, I'd probably go with something like myCin or myStrcpy ...

  8. #8
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Quote Originally Posted by Aisthesis View Post
    Agreed. I think it would be pretty poor programming to name a variable cin or a function strcpy in almost every situation--possible exception being if it's a logical extension of the usual usage but where you need some little extra nuance in the particular situation you're in, but even then, I'd probably go with something like myCin or myStrcpy ...
    Ah, the sweet Java naming convention. Not. Gah. I hate it. Dictator Sun >_<

    Quote Originally Posted by Aisthesis View Post
    I guess what seems weird to me is that in C++ there's only one standard (i.e., part of the language standard) namespace that I've run across, namely std, whereas Java has you using several different packages pretty quickly.
    Yes, for some reason, they seem to merely use namespaces as a way of avoiding name collisions. They could be used to organize functions ala Java, too. I like to do it that way. Nothing wrong with it.

    I've been understanding a Java import statement as telling the compiler where to go to find definitions for the term in question; similarly the C++ #include but not the using, which doesn't tell the compiler anything about where to find the code defining the term in question. As I understand it (which of course may well be wrong), namespaces are just a tool for resolving potential naming conflicts in huge programs, and I don't think that's really the purpose of java packages, which are really more just libraries to use for various specialized tasks.
    No, think of it this way:
    In C++, the compiler knows nothing about any code outside the source files it's compiling. It doesn't know about cin, strcpy, strlen, etc.
    You have to tell the compiler they exist. How? Through declarations.
    So in order to avoid spelling out those declarations every time, we put them inside a file whose contents we can just copy and paste into the current source file.
    Now the compiler can see them, just like Java. But it still doesn't mean you can use std::cin without typing std::cin or using namespace std or using std::cin. The compiler looks for identifiers only in its current namespace (like Java).
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  9. #9
    Registered User
    Join Date
    May 2009
    Posts
    242
    Let me see if I'm following you here:
    In C++, the compiler knows nothing about any code outside the source files it's compiling. It doesn't know about cin, strcpy, strlen, etc.
    You have to tell the compiler they exist. How? Through declarations.
    The declarations you're talking about are #include <iostream> or #include <cstring>, right?

    So in order to avoid spelling out those declarations every time, we put them inside a file whose contents we can just copy and paste into the current source file.
    i.e, a library (again <iostream>, <cstring>, etc.), right? not a namespace, I'm assuming

    Now the compiler can see them, just like Java. But it still doesn't mean you can use std::cin without typing std::cin or using namespace std or using std::cin. The compiler looks for identifiers only in its current namespace (like Java).
    I have some stuff to ask about this part, too, but first I'm going to dig around in some of VS's program files to see how they're structured. For now, I'll just say that a java package corresponds to a path--i.e., import java.util.Scanner; means go to the folder util in your java folder, and there you'll find the file (or I guess possibly files) defining the class Scanner. I'm going to check to see if there's any resemblance in the way the files for compiling C++ programs are organized.

  10. #10
    Registered User
    Join Date
    May 2009
    Posts
    242
    It looks to me like the organization isn't fundamentally different. I'm finding in Visual Studio 08 on my machine under Microsoft Visual Studio 9.0\VC\include all the header folders. Looked at istream, for example, and it looks like a perfectly normal template class declaration--just a pretty intricate one that does things way beyond my current knowledge level.

  11. #11
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by Aisthesis View Post
    Let me see if I'm following you here:

    The declarations you're talking about are #include <iostream> or #include <cstring>, right?
    No, those are preprocessor directives. When the preprocessor encounters the #include directives, the text inside the named files (iostream, cstring, etc) is substituted - straight text pasting - directly into the source code in place of the include directive. The compiler then interprets the resultant source code.

    The declarations Elysia is referring to are contained within those files. Once the preprocessor subsitutes their text into code, the compiler has visibility of the declarations.

    Quote Originally Posted by Aisthesis View Post
    i.e, a library (again <iostream>, <cstring>, etc.), right? not a namespace, I'm assuming
    <iostream>, <cstring>, etc are not libraries. However, the declarations and definitions in those header files are part of the specification of the C++ standard library.

    It is up to the implementation (i.e. the compiler, as implemented) whether the contents of standard headers correspond to library files on the target system (eg .lib or .dll files under windows).
    Quote Originally Posted by Aisthesis View Post
    I have some stuff to ask about this part, too, but first I'm going to dig around in some of VS's program files to see how they're structured. For now, I'll just say that a java package corresponds to a path--i.e., import java.util.Scanner; means go to the folder util in your java folder, and there you'll find the file (or I guess possibly files) defining the class Scanner. I'm going to check to see if there's any resemblance in the way the files for compiling C++ programs are organized.
    There is no such organisation among the C++ standard headers.

    All C and C++ standard headers are placed in some implementation-defined place - the standard say no more than that. Typically, in practice, that is a single directory. With Microsoft compilers - and other compilers that target windows - that directory is a subdirectory named INCLUDE within the directory tree created for installing the compiler itself.

    With some compilers, compiler or system specific header files are placed within sub-directories of that INCLUDE directory. Those arrangements are specific to each compiler and target operating system.

    Your basic problem, at present, is you are interpreting they way C++ does through analogy with what you have learnt previously with Java. Although there are some things in common between Java and C++ (eg similar syntax in some instances) there are many things that are different. The interfacing to the respective standard libraries is one of the areas where Java and C++ have very little in common, so you are wasting your time trying to carry the analogy across.

    There are some things where you need to understand the "C++ way" without relying on analogy to the "Java way". This is one of them.
    Last edited by grumpy; 12-22-2009 at 11:10 PM.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Generalising methods to handle multiple weapon types
    By Swarvy in forum Game Programming
    Replies: 2
    Last Post: 05-22-2009, 02:52 AM
  2. Binary not built with debug info - why?
    By ulillillia in forum C Programming
    Replies: 15
    Last Post: 12-11-2008, 01:37 AM
  3. Turn Based Stradegy System Methods
    By TylerMoyer in forum Game Programming
    Replies: 2
    Last Post: 07-30-2007, 10:45 PM
  4. Lesson #5 - Methods
    By oval in forum C# Programming
    Replies: 1
    Last Post: 05-04-2006, 03:09 PM
  5. Replies: 8
    Last Post: 07-27-2003, 01:52 PM