Functions that take arrays an objects as arguments...

This is a discussion on Functions that take arrays an objects as arguments... within the C++ Programming forums, part of the General Programming Boards category; Hi all, I learned C/C++ a long time ago in high school, and since then I have been working mainly ...

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

    Question Functions that take arrays an objects as arguments...

    Hi all,

    I learned C/C++ a long time ago in high school, and since then I have been working mainly in java. Now I am doing a C++ project again, and I have set up a system of classes and structures that interact with each other.

    This involves several functions taking instances of a class (objects) as arguments, and also a few that take arrays as arguments or return arrays. Its a big complicated project, so I won't post all the code here. But suffice to say, I am getting a ton of errors mostly relating to taking objects or arrays as arguments when both defining a function and when calling that function. I have tried to fix these using pointers to objects/arrays instead, but have had limited success.

    Lets say I want to define a function like this:

    Code:
    int myFunction(int* anArray, myClass anObject)
    Should I do it like that, or with an asterick after myClass as well? And when I call the function, should it look like this:

    Code:
    int myNumbers[7];
    int a;
    myClass someObject(constructorArgument1);
    a = myFunction(myNumbers, someObject);
    Or should there be some more astericks or reference/deReference operators somewhere in the above code? Like I say, I have been working with Java for awhile, and I was never that great with pointers and stuff anyway.

    Is there a site or tutorial that someone knows of that covers functions taking objects/arrays as arguments, or returning them, and when pointers are necessary to do this, and where the reference/dereference operators need to go? I have not found a tutorial that comprehensively covers all of this.

    Thanks guys!

  2. #2
    Just a pushpin. bernt's Avatar
    Join Date
    May 2009
    Posts
    426
    Or should there be some more astericks or reference/deReference operators somewhere in the above code?
    Nope that's good.

    Code:
    int myNumbers[7];
    Here, myNumbers is a pointer to int. The [] operator, which gets values from an array, can be written using pointers, which drives that point home:
    Code:
    myNumbers[3] == *(myNumbers + 3);
    If you're having any trouble with pointers, read through this. Read it at least twice - and let it really sink in.
    Consider this post signed

  3. #3
    Registered User
    Join Date
    Oct 2005
    Posts
    22
    Ok, thanks, that clears things up with arrays. And I probably should have read the article you linked to before posting lol. But one more question. When passing in objects (instances of classes) as arguments to functions, do people usually do that using a pointer? If you don't use a pointer, and then modify the object within the function, will the original object actually be changed, or will it just change a copy of the object within the function?

    Also, I have one function which needs to take in an array of objects (i guess its actually a pointer to an array technically) and that array of objects is itself a member of an instance of a class. Just to make sure Im doing this right, should it look like this?:

    Code:
    // define the function prototype
    int myFunction(myClass* theObjects);
    
    // to call the function
    a = myFunction(anotherObject.objectListArray);
    Do I need any other * or & in there, or should i use "->" instead of a period to access the member array?

    Thanks again for your help!

  4. #4
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,171
    Arguments you pass to function will ALWAYS be copied. So that function will work with a local copy. No changes will be visible outside.
    To get around this, either you pass by address (that is, you take the address with & and pass it, and assign it to a pointer), or you pass by reference. The later is obviously the easiest and simply requires that you put & after the type in the parameter list. Example:

    void myfunc(T* p); // Takes a pointer
    myfunc(&myobj); // Pass address to function

    void myfunc(T& r); // Takes a reference
    myfunc(myobj); // No need to pass address

    However, you are no some deep waters here. If possible, put all arrays inside std::vector or std::array. If you have a C array, then it's just not possible to know its size and buffer overruns are a worry. But with those two, you always have the size at hand and can use the at member function which will throw if you try to access an element that doesn't exist.

    Any and all C arrays will decay to pointers if you pass them to a function. So it doesn't matter where they are--local or part of an object--they will always decay to a pointer and thus you can pass it to a function accepting a pointer. Of course, as noted above, this is bad.
    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.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

  5. #5
    Registered User
    Join Date
    Oct 2005
    Posts
    22
    Thanks for the help guys. I have started work on this program again after a busy week of other commitments. Using your advice, I have cleared up most of the problems. The program is a realtime strategy game. Hence there are many functions within the "unit" class for making that unit interact with other units in the game. This is why there are so many functions that take a reference to the target unit (the target of an attack command or whatever).

    There is one problem I still can't figure out though. I will post some of the relevant code, cutting out stuff thats not related to the problem to keep it short. Below I will list the compiler error. I know its a lot of code to look through but I could really use some help. Thanks.

    Code:
    struct UnitType {
           char name[20];
           int buildTime, finishedTime, mineralCost, vespeneCost, supplyCost, supplyProvided, typeID, minCollectRate, vespCollectRate;
    };
    Code:
    class Unit {
          public:
                 UnitType type;
                 int startTime, finishedTime, deathTime, tempState, currState, ID, builtFromID;
          Unit(int start, int builtfromID, UnitType& tp);
          
    };
    Code:
    Unit::Unit(int start, int builtfromID, UnitType& tp) {
        startTime=start; builtFromID=builtfromID; type=tp;
        finishedTime = startTime+tp.buildTime;
    }
    Code:
    class UnitCollection {
          public:
                 UnitType* theTypes;
                 Unit units[100];
                 int numUnits;
                 void addUnit(int starttime, int builtfromID, UnitType& type);
                 UnitCollection(UnitType* theUnitTypes);
    };
    Code:
    void UnitCollection::addUnit(int starttime, int builtfromID, UnitType& type) {
         Unit theUnit(starttime, builtfromID, type);
         theUnit.currState = 0;
         units[numUnits] = theUnit;
         // theUnit=NULL;
         numUnits++;
    }
    Code:
    UnitCollection::UnitCollection(UnitType* theUnitTypes) {
         theTypes = theUnitTypes;
         numUnits=0;
         addUnit(theTypes[0].buildTime, 0, theTypes[0]);
    }
    The compiler (Dev-Cpp) gives the following errors:

    Code:
    In constructor `UnitCollection::UnitCollection(UnitType*)': 
    no matching function for call to `Unit::Unit()' 
     candidates are: Unit::Unit(const Unit&) 
                     Unit::Unit(int, int, UnitType&) 
    [Build Error]  [UnitCollection.o] Error 1
    Which is weird, because the "Unit" constructor is never called in the "UnitCollection" constructor. Granted, the addUnit function is called, which in turn calls the "Unit" constructor, but it doesn't try to call "Unit::Unit()", it provides the proper arguments. Anyway, this is the only error left after the help you provided earlier, Id really like to get it fixed. Sorry for digging up a thread that may have fallen off the first page. In the future should I make a new one? Thanks again guys!

  6. #6
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,171
    Easy. Unit doesn't have a default constructor, but you don't call an explicit constructor in UnitCollection.
    But disregarding that, I still see a lot of potentially dangerous code. Pointers everywhere. Arrays everywhere. Even char arrays! Ever heard of std::array, std::vector and std::string? Try looking them up and see where you can apply them.
    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.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

  7. #7
    Registered User
    Join Date
    Oct 2005
    Posts
    22
    Easy. Unit doesn't have a default constructor, but you don't call an explicit constructor in UnitCollection.
    Are you talking about where I say "Unit units[100]" in the definition of the "UnitCollection" class? Because the compiler says the error is in the "UnitCollection" constructor, but I never call the "Unit" constructor in the "UnitCollection" constructor.

    I actually intended for the array "Unit units[100]" to be initialized/instantiated in the "UnitCollection" constructor, but I wanted it defined/declared in the class.

    No, I have never heard of std::array or std::vector. I have heard of std::string though, I should change that. Is std:array sort of like the ArrayList class in Java, a wrapper that makes working with arrays more convenient? I will read about these and see how to use them, and maybe incorporate them into my program.

    Thanks again!

  8. #8
    C++まいる!Cをこわせ! Elysia's Avatar
    Join Date
    Oct 2007
    Posts
    22,171
    Quote Originally Posted by cjmdjm View Post
    Are you talking about where I say "Unit units[100]" in the definition of the "UnitCollection" class? Because the compiler says the error is in the "UnitCollection" constructor, but I never call the "Unit" constructor in the "UnitCollection" constructor.
    The constructor of any object will always be called for any object that is created, and any object is constructed/created inside its constructor.
    Thus, UnitCollection's constructor will call Unit's constructor implicitly because you have them defined inside the class.
    By default, the compiler will call the default constructor that takes no arguments. But since such a constructor doesn't exist, it simply spits out an error.
    Since it's an array, you would have to create a default constructor.

    No, I have never heard of std::array or std::vector. I have heard of std::string though, I should change that. Is std:array sort of like the ArrayList class in Java, a wrapper that makes working with arrays more convenient? I will read about these and see how to use them, and maybe incorporate them into my program.
    You might say that. It provides features that integrates them more easily into the standard library containers, algorithms, etc. It also keeps track of its size and has a member function that will throw an exception if you try to access an element that doesn't exist. Handy stuff.
    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.
    For information on how to enable C++11 on your compiler, look here.
    よく聞くがいい!私は天才だからね! ^_^

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Passing 2D arrays between functions
    By taurus in forum C Programming
    Replies: 10
    Last Post: 09-28-2009, 05:05 AM
  2. arrays, functions, HELP
    By beginner1 in forum C Programming
    Replies: 4
    Last Post: 05-20-2009, 03:29 PM
  3. Arrays and Functions
    By w274v in forum C Programming
    Replies: 19
    Last Post: 11-03-2005, 12:47 PM
  4. Arrays and Functions
    By KunoNoOni in forum Game Programming
    Replies: 12
    Last Post: 10-04-2005, 09:41 PM
  5. elements of arrays; functions
    By sballew in forum C Programming
    Replies: 6
    Last Post: 09-03-2001, 01:48 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21