Thread: Function that returns a class...

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    22

    Function that returns a class...

    So I am working on a software based 3d engine. I have a structure called triangle, and a class called object. The object class contains an array of triangles that make up that object, and position/orientation data.

    Anyway, I am writing a function called createCube, which is supposed to return an instance of object (or a pointer to an instance of object). The returned object will contain a bunch of triangles that together resemble a cube (duh). Anyway, Im having some difficulty writing this function. This is what I have, minus the irrelevant parts:

    Code:
    object createCube(int xpos, ..... )
    {
       triangle theTriangles[12];
       //.....
       //code to set triangles to form cube
       //......
    
       object theCube = new object(xpos, ypos, zpos,0,0,0);
       for (int i=0;i<12;i++)
       {
          theCube.addTriangle(theTriangles[i]);
       }
       return theCube;
    }
    This does not compile. It says "conversion from 'object*' to nonscalar type 'object' requested" on the line "object theCube= new obj...." So I added a couple astericks (*), changing it to:

    Code:
    object* createCube(int xpos, ..... )
    {
       triangle theTriangles[12];
       //.....
       //code to set triangles to form cube
       //......
    
       object* theCube = new object(xpos, ypos, zpos,0,0,0);
       for (int i=0;i<12;i++)
       {
          theCube.addTriangle(theTriangles[i]);
       }
       return theCube;
    }
    But now, it finds a problem with the line "theCube.addTriangle(....)" It says that addTriangle has not been declared (it has) and that their is a request for member of non-aggregate type before '(' token. I tried putting a '&' in front of that line, but it didn't help.

    I know the problem has something to do with pointers and reference and dereference operators or something like that. I know its sad that I can figure out 3d math, but not simple classes and pointers. Can anyone help me out? It would be greatly appreciated.

    Thanks!
    Last edited by cjmdjm; 02-20-2009 at 06:23 PM.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    So you can't use . on a pointer. Fortunately for all, you can use -> on a pointer.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    theCube is a pointer, so you can't use theCube.addTriangle. You need something other than that '.'.

    Also, is there a reason you are using a pointer here? If your object class is setup properly, you can just return it instead of using new. With your current code you risk a memory leak if the calling function doesn't call delete on the pointer it gets from the function, and error handling will be harder.

    To implement that solution, change the line with "new" in the first piece of code to this:
    Code:
    object theCube(xpos, ypos, zpos,0,0,0);

  4. #4
    Registered User
    Join Date
    Oct 2005
    Posts
    22
    Ok, so both tabstop and Daved's solutions work fine. Thanks guys. But, in the interest of bettering my understanding of classes/pointers, what exactly does the "new" keyword do? I thought to create an instance of a class you always did:

    Code:
    object theCube = new object(...);
    But what Daved said also works, I didn't know you could do that. I guess using the line above with the "new" keyword makes theCube a pointer? And the other way doesn't?

    Thanks!

  5. #5
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    new gives you some memory (or throws an exception) that is suitable to store the object in. It also calls the constructor for the object. new gives back a pointer, and obviously, you can not make an object out of a pointer to an object.

    Whether you need a pointer or a regular object is often quite hard to answer. It is one of those that you have to understand from how the object is being used which it is right or wrong (and it may not be CLEAR that one is right and one is wrong, they may be "OK" both of them [or extremely rare "neither"]).

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  6. #6
    Registered User
    Join Date
    Oct 2005
    Posts
    22
    new gives you some memory (or throws an exception) that is suitable to store the object in. It also calls the constructor for the object.
    So if I don't use "new" does it not call the constructor? Because I was using Daved's method, but I want the constructor to be called, to initialize the position and orientation data.

    Thanks.

  7. #7
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Quote Originally Posted by cjmdjm View Post
    So if I don't use "new" does it not call the constructor? Because I was using Daved's method, but I want the constructor to be called, to initialize the position and orientation data.

    Thanks.
    Just declaring an object will always call the constructor (and in fact Daved gave you the syntax for such).

  8. #8
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Quote Originally Posted by cjmdjm View Post
    So if I don't use "new" does it not call the constructor? Because I was using Daved's method, but I want the constructor to be called, to initialize the position and orientation data.

    Thanks.
    Sorry if I gave that impression (something to do with "I know what I mean" and other people reading it differently ). No, of course, when you use a local object like that, the constructor is being called too.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  9. #9
    Registered User
    Join Date
    Oct 2005
    Posts
    22
    Awesome thanks guys. On a completely unrelated note, my program is starting to get really long, with lots of class and function declarations ahead of the main function. I was thinking of separating some or all of these to another source file or header file or dll or something to clean it up. If I wanted to use a header file, is this hard to do? Do I just cut/paste the function/class/structure declarations to the new header file and then say #include header.h at the top? Or is it not that simple? Do I have to go into the compiler/linker settings and tell it to use the header? What can I move to the header? Classes? functions? Everything but the main function?

    Thanks guys.

  10. #10
    Kernel hacker
    Join Date
    Jul 2007
    Location
    Farncombe, Surrey, England
    Posts
    15,677
    Right. Splitting source-code "right" is an art that you learn from experience.

    However, for most purposes, this is a good starting point:
    Each class is declared in a header-file, usually named to correspond with the class. E.g "myclass.h".

    The function definitions for that class (except for real trivial functions, such as access functions [setter/getter functions]) go in a source file of the same name, e.g "myclass.cpp"

    The main function is put in a file that corresponds to the application itself, e.g. "myapp.cpp". It includes the header file(s) that it needs to do it's work.

    If one class relies on another class, it should include that header file in its header file. So if you have "mybase.h" and "myderived.h", then "mybase.h" would be included by "myderived.h". That way, the programmer that uses "myderived.h" doesn't need to know that "mybase.h" needs to be included as well.

    You should have "include-guards" in your header file to prevent the same header file being included multiple times. This is a pattern like this:
    Code:
    #ifndef SOMEFILE_H
    #define SOMEFILE_H
    ... stuff of the header here ...
    #endif
    That way, if you have for example:
    Code:
    #include "myderived.h"
    #include "mybase.h"
    there won't be an error because mybase.h is included twice.

    You should not involve DLL's at this point.

    --
    Mats
    Compilers can produce warnings - make the compiler programmers happy: Use them!
    Please don't PM me for help - and no, I don't do help over instant messengers.

  11. #11
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    Regarding the objects versus pointers, I would suggest always using objects unless you have a specific reason not to. You rarely need to use new in a C++ program. If you are using new anywhere in your program you should take a closer look and see if it is really necessary.

    In Java, you have to use new to create objects, but in C++ you can use local objects that are automatically handled in memory. If you use new in C++, you generally have to manage the memory yourself, which can be unnecessary and difficult to get right.

  12. #12
    Registered User
    Join Date
    Oct 2005
    Posts
    22
    #ifndef SOMEFILE_H
    #define SOMEFILE_H
    ... stuff of the header here ...
    #endif
    In the above code, why #define SOMEFILE_H, and not #include SOMEFILE_H? Perhaps I don't understand the difference between include and define. And the #endif goes at the very end of the header file? Seems odd.

    Also, I have to include header files, eg, #include file.h, but do I have to do the same for .cpp files, eg, #include file.cpp, if I have more than just the main one? And do I need to adjust compilier or linker settings or paths?

    And in most of my programs, I define all of a class's functions within the class declaration, eg,

    Code:
    class object
    {
       public:
       void addTriangle(...)
       {
          //code
       }
       //etc
    };
    as opposed to

    Code:
    class object
    {
       public:
       void addTriangle(...);
       //etc
    };
    void object::addTriangle(...)
    {
       //code
    }
    Is this bad or not the standard way to do it? Is this a problem if I want to move the class to a header file? ie, do the function declarations have to be in a ".cpp" file but the class itself in a ".h" file?

    Sorry to ask so many questions but this is the kind of thing you don't see in tutorials. There are plenty of tutorials on how to use for loops, if statements, classes, etc, but few on how to use header files in your program, or multiple source files, or DLLs, etc.

    And yeah, as Daved alluded to, I learned most of what I know about Object Oriented stuff (eg, classes) in Java. I have known C for years, but last year I was required to take a Java class for my major, and finally learned object oriented stuff. But I didn't like Java, and switched to C++ without doing much research on the differences in how classes are handled.

    Thanks.
    Last edited by cjmdjm; 02-20-2009 at 08:19 PM.

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    It is perhaps sometimes appropriate to #include a .cpp file, but I can't think of a reason why (other than template functions in a file called .cpp).

    You can only #include a file. SOMEFILE_H isn't a file, it's a name. #define defines the name as a macro.

    If the definition of a function is longer than say one or two lines, it's usually considered bad practice to put that function in the class definition itself -- the class definition is usually considered "interface" (that is, a list of all the things the class can do, not how it all happens).

    When you end up with more than one .cpp file, you have to compile them all together (this happens by putting all the filenames in one gcc command/putting all your files in one project in your IDE/something similar depending on how you compile).

  14. #14
    Registered User
    Join Date
    Oct 2005
    Posts
    22
    Ok, I found the preprocessor directives tutorial on this site and that is helping with a lot of this. I didn't know these things were called preprocessor directives so at first I didn't know there was a tutorial on them.

    So how do you decide whether to put a function/class/structure definition in a ".h" file or another ".cpp" file? Are their restrictions on what can go in a ".h" file and what has to go in another ".cpp" file? Again, this is the sort of thing I haven't been able to find tutorials on.

    Oh, and what is a DLL? Pretty much every program you buy has DLL files along with its EXE file, in fact my 3d engine that I am writing has to have SDL.dll to work. But I don't really know what a DLL is and I have never written my own. When is it a good idea to write a DLL?

    Thanks guys.

  15. #15
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Code goes in .cpp files. Non-code goes in .h files. For this purpose, non-code would be class definitions and function prototypes.

    DLL just stands for dynamic link library, which not surprisingly has a wiki page (among other resources). Presumably a library is a DLL (as opposed to a static library) if either (a) it's so large that no one would want to have all that included in their executable (b) you expect many different programs to be using it at the same time, so why not just have one copy loaded in memory (c) you expect the library, and the library only, to change relatively often, so allowing your users to replace the old DLL with the new DLL without re-compiling all their code is a Good Thing.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Calling a Thread with a Function Pointer.
    By ScrollMaster in forum Windows Programming
    Replies: 6
    Last Post: 06-10-2006, 08:56 AM
  2. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  3. c++ linking problem for x11
    By kron in forum Linux Programming
    Replies: 1
    Last Post: 11-19-2004, 10:18 AM
  4. Is it possible to have callback function as a class member?
    By Aidman in forum Windows Programming
    Replies: 11
    Last Post: 08-01-2003, 11:45 AM
  5. Contest Results - May 27, 2002
    By ygfperson in forum A Brief History of Cprogramming.com
    Replies: 18
    Last Post: 06-18-2002, 01:27 PM