The new forums will be named Coin Return (based on the most recent vote)! You can check on the status and timeline of the transition to the new forums here.
The Guiding Principles and New Rules document is now in effect.

Pointers and Classes, arg (C++)

Sir CarcassSir Carcass I have been shown the end of my worldRound Rock, TXRegistered User regular
edited February 2010 in Help / Advice Forum
I had a big thing typed up, but I think I figured out my problem.

Does
Player *playerListHead;

Player *tmp_ptr = playerListHead;

playerListHead = new Player();

and
Player *playerListHead;

Player *tmp_ptr;

playerListHead = new Player();
tmp_ptr = playerListHead;

end up with tmp_ptr having the same value?

Sir Carcass on
«1

Posts

  • KakodaimonosKakodaimonos Code fondler Helping the 1% get richerRegistered User regular
    edited February 2010
    Yes. playerListHead and tmp_ptr are pointing to the same memory location in both examples.

    Kakodaimonos on
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    Well for some reason, the first caused my program to crash when accessing tmp_ptr, and the other does not.

    Sir Carcass on
  • TejsTejs Registered User regular
    edited February 2010
    The first sample would crash because it's a null pointer. playerListHead was not assigned a location in memory at the time tmp_ptr was assigned, so attempting to dereference it would cause a crash.

    Tejs on
  • KakodaimonosKakodaimonos Code fondler Helping the 1% get richerRegistered User regular
    edited February 2010
    So you were doing:

    tmp_ptr->Foobar();

    ?

    Kakodaimonos on
  • CelestialBadgerCelestialBadger Registered User regular
    edited February 2010
    Well for some reason, the first caused my program to crash when accessing tmp_ptr, and the other does not.

    playerListHead had not been assigned a value when it's value was assigned to tmp_ptr, in the first example. Therefore tmp_ptr remained undefined even when playerListHead was assigned a value.

    What you want to google to solve all your problems is "copy constructor" - but to start you off:

    http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.html

    CelestialBadger on
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    Okay, that's what I thinking. I guess I posed the question wrong. I figured the "new" was the key.

    I don't think a copy constructor is necessary for what I'm doing, at least here. In another part, I have something like this:
    Player PC();
    
    playerListHead = new Player();
    
    *playerListHead = PC;
    

    Is that sufficient, or would a copy constructor be better?

    Sir Carcass on
  • TejsTejs Registered User regular
    edited February 2010
    I'm not sure what you are trying to do. If you're trying to make a new instance, and have two pointers pointing to it, you would do like your second example.

    A copy constructor is only necessary when you need to make a deep copy of all the members of your initial object.

    Are you trying to make a linked list?

    Tejs on
  • khainkhain Registered User regular
    edited February 2010
    Just in case Tejs wasn't clear, Kakodaimonos is wrong and the tmp_ptr does not end with the same value in both examples. In the first example tmp_ptr is either garbage or null since you set it equal to a uninitialized pointer and then initialized the head pointer. In the second example you initialize the head pointer first and then do the assignment

    I don't think you need to do this, but you can use a pointer to a pointer in the first example and it would work then since you'd have tmp_ptr point to the head pointer and then you can assign or change where head pointer points and dereferencing tmp_ptr would give you the head pointer.

    edit: You may want to explain what you're trying to do in the latest piece of code you posted, since it will do something, but that may not be what you intended.

    khain on
  • DaedalusDaedalus Registered User regular
    edited February 2010
    Player *playerListHead; //playerListHead = some random fucking value
    
    Player *tmp_ptr = playerListHead; //tmp_ptr = some random fucking value
    
    playerListHead = new Player(); //playerListHead = the memory address of your new Player
    

    tmp_ptr is still some random fucking value. Depending on your compiler, it might be NULL, or it might not. If it isn't, you might not even crash, you might silently access some other random chunk of your program's memory, which is where C++ gets really fun.
    Player *playerListHead;//playerListHead = some random fucking value
    
    Player *tmp_ptr;//tmp_ptr = some random fucking value
    
    
    playerListHead = new Player(); //playerListHead = the memory address of your new Player
    tmp_ptr = playerListHead; //playerListHead = the memory address that same new Player
    

    Remember, a pointer is basically an unsigned int that contains a memory address.

    Daedalus on
  • mspencermspencer PAX [ENFORCER] Council Bluffs, IARegistered User regular
    edited February 2010
    I had a big thing typed up, but I think I figured out my problem.

    Does
    Player *playerListHead;
    
    Player *tmp_ptr = playerListHead;
    
    playerListHead = new Player();
    

    and
    Player *playerListHead;
    
    Player *tmp_ptr;
    
    playerListHead = new Player();
    tmp_ptr = playerListHead;
    

    end up with tmp_ptr having the same value?

    You've been given some bad advice. Those segments are not the same, semantically. (Meaning-wise, that is.) The first code segment would need yet another assignment statement, similar to the last line of the second code segment.

    If you really want to save time you could go:
    Player *tmp_ptr = playerListHead = new Player();
    But only people who really understand expression evaluation and side-effects will get what you're doing right away. So it's never a good idea for real world code. It's kinda needlessly obscure.
    Player *tmp_ptr = (the value of some expression)
    The expression is (playerListHead = new Player()). The "meaning" of that expression is the output of (new Player()), and while being evaluated that expression has a side-effect of storing the value of (new Player()) in playerListHead.
    That value (having been first returned from new Player() and then stored into playerListHead) is now computed and can be assigned to tmp_ptr.

    mspencer on
    MEMBER OF THE PARANOIA GM GUILD
    XBL Michael Spencer || Wii 6007 6812 1605 7315 || PSN MichaelSpencerJr || Steam Michael_Spencer || Ham NOØK
    QRZ || My last known GPS coordinates: FindU or APRS.fi (Car antenna feed line busted -- no ham radio for me X__X )
  • CelestialBadgerCelestialBadger Registered User regular
    edited February 2010
    Is that sufficient, or would a copy constructor be better?

    A copy constructor is only useful if you are trying to copy the contents of the Player object. Is that what you are trying to do? Or do you want two pointers to the same instance of an object?

    I don't see what the code you posted is meant to do.

    CelestialBadger on
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    Well, you guys tell me.

    Basically, this is my current plan. I have a PC instance of the Player class that will handle the player's info. I have the 5 member array of the Player class to use for my 4 main NPCs (leaving the 0 index alone). I want to then have a linked list of every head of household that the game creates (including the PC and 4 NPCs), with linked lists coming off of each of those with their family members. Currently, I'm creating the PC, creating the 4 NPCs, then creating a linked list (will start with 5 elements linked) and copying the PC and NPC[] contents to them. Any of the 4 NPCs can be replaced by another family at any time.

    I could also just use one linked list and keep an array of IDs. That might work better. I was mainly just curious about copying instances of classes, and if my suspicions were correct about why the 2 code bits created different results (I was).

    Sir Carcass on
  • TejsTejs Registered User regular
    edited February 2010
    Well, you guys tell me.

    Basically, this is my current plan. I have a PC instance of the Player class that will handle the player's info. I have the 5 member array of the Player class to use for my 4 main NPCs (leaving the 0 index alone). I want to then have a linked list of every head of household that the game creates (including the PC and 4 NPCs), with linked lists coming off of each of those with their family members. Currently, I'm creating the PC, creating the 4 NPCs, then creating a linked list (will start with 5 elements linked) and copying the PC and NPC[] contents to them. Any of the 4 NPCs can be replaced by another family at any time.

    I could also just use one linked list and keep an array of IDs. That might work better. I was mainly just curious about copying instances of classes, and if my suspicions were correct about why the 2 code bits created different results (I was).

    So you have a linked list of HeadOfHouseholds. Each HeadOfHousehold has a linked list of family members. The Player and NPC are the starting elements of the HeadOfHouseholds linked list?

    Tejs on
  • ZekZek Registered User regular
    edited February 2010
    What's important is that you understand what exactly a pointer is - how they behave is completely logical from there. A pointer is just a variable like anything else, except instead of a value it stores a memory address. Its data type is just a helpful tip for C to know what type of object it points to. The * operator is like a function that takes a pointer as an argument and returns the object located at the address stored in the pointer(it's also used completely separately to initialize a variable as a pointer because somebody was retarded).

    If you want to make a new object you need to instantiate a new object, pointers have nothing to do with it. You can make a dozen copies of the pointer pointing to an object, but all it will get you is thirteen pointers pointing to that object. So if you want to make a new player object, there is no way to do it other than with "new Player()." Copy constructors are what you want for making a new object that's identical to an existing one.

    In your first example, playerListHead has a value of null at first because you didn't define it. So then you gave tmp_ptr a value of null as well(i.e. line 2 did nothing). And only then did you define playerListHead - tmp_ptr is still null.

    The second example will result in two pointers that are completely identical - they point to the same object and you can use them interchangeably.

    Zek on
  • GoetterdaemmerungGoetterdaemmerung Registered User regular
    edited February 2010
    Well, you guys tell me.

    Basically, this is my current plan. I have a PC instance of the Player class that will handle the player's info. I have the 5 member array of the Player class to use for my 4 main NPCs (leaving the 0 index alone). I want to then have a linked list of every head of household that the game creates (including the PC and 4 NPCs), with linked lists coming off of each of those with their family members. Currently, I'm creating the PC, creating the 4 NPCs, then creating a linked list (will start with 5 elements linked) and copying the PC and NPC[] contents to them. Any of the 4 NPCs can be replaced by another family at any time.

    I could also just use one linked list and keep an array of IDs. That might work better. I was mainly just curious about copying instances of classes, and if my suspicions were correct about why the 2 code bits created different results (I was).
    You might be asking two things at once here. If you're asking us for the C++ syntax used to organize your classes into a linked list (or whatever), we can do that if you give us the name of the classes and how you want them organized (I gather it has something to do with a short linked list) -- although your reasons for wanting specifically a linked list might be interesting. We don't need to know how your program works but we do need to know what the involved classes look like. The only class I see in your post is Player, but you're mentioning more than one different idea/structure (Player, PC, NPC, head of household).

    On the other hand if you're asking us for opinions on your choice of classes/datastructures given your project, you need to tell us more about your project, and a higher level view of how you want it organized.

    Goetterdaemmerung on
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    Nah, I can figure out the syntax well enough. I was just curious as to if I was copying data from one instance to another correctly by dereferencing it.

    But if you have a better idea for a data structure, I'd be glad to hear it. This is what I'm thinking now.
    PC--->NPC--->NPC--->etc
     |     |             | 
     V    V            V
     wife  wife        wife
     |                   |
     V                   V
     son                son
                           |
                           V
                       daughter
    

    Sir Carcass on
  • ZekZek Registered User regular
    edited February 2010
    It depends completely on the specifics of the project. For example if each Player can have only one wife, son and daughter then you're better off having one field for each in the class definition. Then you never have to bother with the list logic, it's more efficient and the code is much more readable. Or one wife field and one children list, etc. As for the primary list of players, linked lists are better for quickly adding/removing elements and arrays are better for quickly retrieving elements.

    Zek on
  • cliffskicliffski Registered User regular
    edited February 2010
    Are you actually coding your own linked list from scratch? If so, please don't. Most big studios do not. Every place I worked uses STL for this sort of stuff. Writing your own linked list code will likely make ti inefficient, buggy and generally will waste time.
    Its fun to do when learning I guess, but I'd be terrified of relying on my own hacked together container classes these days :D

    cliffski on
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    Yeah, I write my own. Mainly because I never learned to use the STL version, but also to help learn. I don't really do much complicated stuff with them here.

    And the family members are dynamic.

    For those curious, this is the current version of the Player class:
    class Player
    {
    
    public:
    
       Player();
       Player(int);
       Player(int, int, int, int, int);
       int ID;
       string firstName;
       string houseName;
       int hp;
       int honor;
       int sword;
       int lance;
       int general;
       int finance;
       int rank;
       int provinces;
       int troops;
       int gold;
       int birthdate;
    
       void setID(int);
       int getID();
       void setFirstName(string);
       string getFirstName();
       void setHouseName(string);
       string getHouseName();
       string getName();
       void setHP(int);
       int getHP();
       void setHonor(int);
       int getHonor();
       void setSword(int);
       string getSword();
       void setLance(int);
       string getLance();
       void setGeneral(int);
       string getGeneral();
       void setFinance(int);
       string getFinance();
       void setRank(int);
       string getRank();
       void setProvinces(int);
       int getProvinces();
       void setTroops(int);
       int getTroops();
       void setGold(int);
       int getGold();
       void setBirthdate(int);
       int getBirthdate();
    
       Player * next;
       Player * getNext();
       void setNext(Player *);
    
    };
    

    Sir Carcass on
  • CelestialBadgerCelestialBadger Registered User regular
    edited February 2010
    You are right to not use the STL. When you have got this list working you will know a lot about C++ that many people never master. There is a good reason most of the first year of my Computer Science coding classes involved writing linked lists - once you can write a good linked list, you'll have a good understanding of the language.

    When I was learning C++ I used this site as a reference:

    http://www.parashift.com/c++-faq-lite/

    It's heavy going, so don't read it all at once.

    CelestialBadger on
  • bowenbowen Sup? Registered User regular
    edited February 2010
    I recommend cplusplus.com/ref/ for that stuff too:

    http://www.cplusplus.com/doc/tutorial/
    http://www.cplusplus.com/ref/

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    I use cplusplus.com quite regularly.

    And although it seems the contrary, I'm not new to C++. :P (I'm 6 classes away from a BS in CS that I'll probably never finish.) It's just been a few years since I've used some of this stuff, so I'm trying to shake off the rust. I program these little games when I don't have other stuff to do at work for fun and to remember this stuff.

    Sir Carcass on
  • bowenbowen Sup? Registered User regular
    edited February 2010
    I love that place.

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • GoetterdaemmerungGoetterdaemmerung Registered User regular
    edited February 2010
    Okay you're implementing the linked list directly in the Player class (this works; another more common way to do it is to implement a new LinkedList class that only has two fields: a pointer to the next LinkedList item and a pointer to a Player item).

    To get the linked list working, you just need setNext() , which is one line of code (next = p;). Now you'll probably need some more interesting functions that actually do something to the list (given the first Player in the linked list). What kind of things do you want to do to the list?

    Don't forget to initialize 'next' to NULL somewhere -- some c++ compilers don't do that for you.

    e: also I don't see the household-organizing stuff. You mentioned using an array, someone else mentioned using a couple pointers for wife/daughter/etc. Depends on your idea of a household.

    Goetterdaemmerung on
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    Yeah, I haven't started on the family members yet. Still figuring out how I want to do that. The array was for probably having something like int NPC[5] and then storing IDs in there for who are the current 4 opponents. I'll then use those IDs to reference people in the linked list.

    This is what I have for using the list so far:
    void newGame()
    {
       Player *tmp_ptr;
    
       createChar();
       TCODConsole::root->clear();
       drawMessageBox("Put intro text here",1,1,15,15,70,45);
       
       for(int i=1;i<5;i++)
       {
          NPC[i].setFirstName(TCODNamegen::generate("male first"));
          NPC[i].setHouseName(TCODNamegen::generate("last"));
          while(!nameOK(NPC[i].getHouseName()))
             NPC[i].setHouseName(TCODNamegen::generate("last"));
          houseList[i] = NPC[i].getHouseName();
          NPC[i].setSword(rng->getInt(1,4));
          NPC[i].setLance(rng->getInt(1,4));
          NPC[i].setGeneral(rng->getInt(1,4));
          NPC[i].setFinance(rng->getInt(1,4));
          NPC[i].setBirthdate(438000 - rng->getInt(7300,20000));
    
          NPC[i].setRank(rng->getInt(1,4));
    
          NPCcurrent[i] = NPC[i];
       }
    
       playerListHead = new Player();
       *playerListHead = PC;
       tmp_ptr = playerListHead;
    
       int i = 1;
    
       while(i<5)
       {
          tmp_ptr->setNext(new Player());
          tmp_ptr = tmp_ptr->getNext();
          *tmp_ptr = NPC[i];
          i++;
       }
    
    }
    

    Sir Carcass on
  • GoetterdaemmerungGoetterdaemmerung Registered User regular
    edited February 2010
    Yeah, I haven't started on the family members yet. Still figuring out how I want to do that. The array was for probably having something like int NPC[5] and then storing IDs in there for who are the current 4 opponents. I'll then use those IDs to reference people in the linked list.

    This is what I have for using the list so far:
    void newGame()
    {
       Player *tmp_ptr;
    
       createChar();
       TCODConsole::root->clear();
       drawMessageBox("Put intro text here",1,1,15,15,70,45);
       
       for(int i=1;i<5;i++)
       {
          NPC[i].setFirstName(TCODNamegen::generate("male first"));
          NPC[i].setHouseName(TCODNamegen::generate("last"));
          while(!nameOK(NPC[i].getHouseName()))
             NPC[i].setHouseName(TCODNamegen::generate("last"));
          houseList[i] = NPC[i].getHouseName();
          NPC[i].setSword(rng->getInt(1,4));
          NPC[i].setLance(rng->getInt(1,4));
          NPC[i].setGeneral(rng->getInt(1,4));
          NPC[i].setFinance(rng->getInt(1,4));
          NPC[i].setBirthdate(438000 - rng->getInt(7300,20000));
    
          NPC[i].setRank(rng->getInt(1,4));
    
          NPCcurrent[i] = NPC[i];
       }
    
       playerListHead = new Player();
       *playerListHead = PC;
       tmp_ptr = playerListHead;
    
       int i = 1;
    
       while(i<5)
       {
          tmp_ptr->setNext(new Player());
          tmp_ptr = tmp_ptr->getNext();
          *tmp_ptr = NPC[i];
          i++;
       }
    
    }
    
    We need to see how you declared PC, NPC, playerListHead. Once you put that in I see a couple that can probably be clarified!

    Goetterdaemmerung on
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    Player PC(0);
    Player NPC[5];
    Player NPCcurrent[5];
    
    Player *playerListHead;
    

    Sir Carcass on
  • GoetterdaemmerungGoetterdaemmerung Registered User regular
    edited February 2010
    There are two ways to allocate a new object in c++:

    1) Simply declare the variable. "Player PC;" (I'm not sure why you put a (0) after PC -- afaik this should throw a compile error?) will create a new Player automatically. It's called an automatic object. Automatic objects are automatically de-allocated (destroyed, pointers to them will blow up if you use them) once they fall out of scope. I'm guessing you declared them in a static scope, i.e. of your main.cpp, so this shouldn't cause any problems for you (but be aware, if you had declared them inside "void newGame()", you would have problems when trying to use these objects once newGame returned)

    2) Use the new keyword. This is kind of like using malloc, if you're familiar. The expression "new Player" allocates space for a Player object and evaluates to that memory address -- so you'll want to assign it to a Player *pointer, like *playerListHead ("playerListHead = new Player"), or pass it to a function that's expecting a pointer, like setNext(). The expression "new Player()" does all of this and then calls the Player() constructor, if there is one.

    I'm guessing that createChar() fills in various parts of the PC Player object. Then you have a loop which fills in parts of the NPC Player object array (looks fine). Then you want to link those five Player objects into a linked list using the linked list that you built into the Player class.

    You do not need to say:
    playerListHead = new Player();
    
    I think here you're trying to allocate your PC Player object -- but you've already done it with the "Player PC" declaration. This line doesn't do anything good or bad (you're basically telling playerListHead to point at a brand new Player object you're creating, then with the very next line immediately telling it to point to the original PC Player object you created instead (leaving that brand new Player object cold and lonely, never to be pointed to or used again).

    Similarly with your while loop:
    while(i<5)
      {
          tmp_ptr->setNext(new Player());
          tmp_ptr = tmp_ptr->getNext();
          *tmp_ptr = NPC[i];
          i++;
      }
    

    You don't need to allocate new Player objects -- you've already allocated them (which you know -- you just spent a big loop filling them with random ints). You just need to set the '*next' pointer in each Player to the next Player in your list. It should look like this:
    while(i<5)
      {
          tmp_ptr->setNext(&NPC[i]);
          tmp_ptr = tmp_ptr->getNext();
          i++;
      }
    

    setNext(*Player) is expecting a pointer to (i.e., memory address of) another Player object. NPC is that player object, and &NPC is the address of it. The & operator gives you the address of a variable.
    Then "tmp_ptr = tmp_ptr->getNext()" moves tmp_ptr to point at the Player list item that you just linked up to the end of the list.

    C++ pointer operations are tricky and even I had to look up some stuff to make sure I wasn't misinforming. Definitely read as much as you can about c/c++ pointers -- they work the same in c and c++, c++ just adds some stuff relating to objects (so, the "->" and "." operators).

    Goetterdaemmerung on
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    (I'm not sure why you put a (0) after PC -- afaik this should throw a compile error?)
    Player::Player()
    {
       ID = 0;
       firstName = "";
       houseName = "";
       hp = 100;
       honor = 50;
       sword = 1;
       lance = 1;
       general = 1;
       finance = 1;
       rank = 1;
       provinces = 1;
       troops = 1000;
       gold = 500;
       next = NULL;
       birthdate = 438000;
    }
    
    Player::Player(int i)
    {
       ID = i;
       firstName = "";
       houseName = "";
       hp = 100;
       honor = 50;
       sword = 1;
       lance = 1;
       general = 1;
       finance = 1;
       rank = 1;
       provinces = 1;
       troops = 1000;
       gold = 500;
       next = NULL;
       birthdate = 438000;
    }
    

    So yeah, for the PC (who I wanted as ID 0), I can just use the default constructor. For the NPCs, I'll use that for IDs.

    As far as the other stuff, what I had been doing was keeping playerListHead as a separate entity from PC and NPC[] and copying the contents back and forth. Is that not what I did? The better solution is probably to have both pointers pointing to the same thing, but I wasn't comfortable enough in my knowledge of pointers to do that.

    Sir Carcass on
  • CelestialBadgerCelestialBadger Registered User regular
    edited February 2010
    Player::Player(int i = 0)
    {
       ID = i;
       firstName = "";
       houseName = "";
       hp = 100;
       honor = 50;
       sword = 1;
       lance = 1;
       general = 1;
       finance = 1;
       rank = 1;
       provinces = 1;
       troops = 1000;
       gold = 500;
       next = NULL;
       birthdate = 438000;
    }
    
    


    Default parameters = win. It's always better to have less copy paste code duplication - it tends to get inconsistent and thus buggy.

    CelestialBadger on
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    Player::Player(int i = 0)
    


    Default parameters = win. It's always better to have less copy paste code duplication - it tends to get inconsistent and thus buggy.

    So I assume that will use 0 unless something else is provided? If so, that's pretty neat. I've never seen that.

    Sir Carcass on
  • CelestialBadgerCelestialBadger Registered User regular
    edited February 2010
    So I assume that will use 0 unless something else is provided? If so, that's pretty neat.

    Yep! I use it all the time.

    CelestialBadger on
  • bowenbowen Sup? Registered User regular
    edited February 2010
    And this is one of the #1 reasons I hate C#.

    bowen on
    not a doctor, not a lawyer, examples I use may not be fully researched so don't take out of context plz, don't @ me
  • SevorakSevorak Registered User regular
    edited February 2010
    Player::Player(int i = 0) :
       ID(i),
       firstName(""),
       houseName(""),
       hp(100),
       honor(5),
       sword(1),
       lance(1),
       general(1),
       finance(1),
       rank(1),
       provinces(1),
       troops(1000),
       gold(500),
       next(NULL),
       birthdate(438000)
    {
    }
    
    


    Default parameters = win. It's always better to have less copy paste code duplication - it tends to get inconsistent and thus buggy.

    I've always been taught that initializing variables like this is better as well.

    Also, if you separate declaration and definition of your functions into .h and .cpp files, which you should, the default parameters only go in the declaration (the .h part). Putting it in the definition as well will cause a compiler error.

    Sevorak on
    steam_sig.png 3DS: 0748-2282-4229
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    So I assume that will use 0 unless something else is provided? If so, that's pretty neat.

    Yep! I use it all the time.

    So how does that work with declaring constructors? Would I need Player() and Player(int)?

    Edit: Ah, I see.

    Sir Carcass on
  • GoetterdaemmerungGoetterdaemmerung Registered User regular
    edited February 2010
    As far as the other stuff, what I had been doing was keeping playerListHead as a separate entity from PC and NPC[] and copying the contents back and forth. Is that not what I did? The better solution is probably to have both pointers pointing to the same thing, but I wasn't comfortable enough in my knowledge of pointers to do that.

    playerListHeader is a pointer, but PC and NPC are actual objects. In other words, when you declare this:
    Player PC(0);
    Player NPC[5];
    
    Player *playerListHead;
    
    The compiled program will allocate 500 bytes of memory (lets say thats how big a Player object is) for PC, then 2500 bytes of memory for NPC, then 4 bytes of memory for playerListHead. playerListHead is not a Player, it's just a 4-byte pointer that you can use to point at a Player. I'm not sure what you mean by 'copying contents' -- from what I can see, you never, nor would need to, copy the contents of a Player. What I gather you *might* want to do is have Players relate to each other in different ways (i.e. changing the heads of households, removing Players from the game), but all that should require is changing/swapping pointers (making pointers point to different Player objects).

    If that went over your head, lemme know where I lost you.

    Goetterdaemmerung on
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    No, I got it. What I meant was, PC and NPC are temporary containers, and data from the linked list will be copied into them as needed. Think of it this way, the linked list is PlayerName->John->Mark->Joe->Henry->William->Terry. PC contains the info of PlayerName. NPC1 contains the info of John. NPC2 contains the info of Mark, etc up through Henry. William and Terry are in the list, but not used at the moment. Henry is killed and he has no heirs, so William is promoted to take his place. His info is now copied into NPC4.

    Basically, I'm making a medieval Europe version of Sword of the Samurai, if you're familiar with that. The 4 NPC's are your current opponents. It's like a boardgame with 5 players.

    Sir Carcass on
  • CelestialBadgerCelestialBadger Registered User regular
    edited February 2010
    If Henry is killed, delete Henry, and copy the pointer to William over into the NPC array of pointers.

    CelestialBadger on
  • Sir CarcassSir Carcass I have been shown the end of my world Round Rock, TXRegistered User regular
    edited February 2010
    If Henry is killed, delete Henry, and copy the pointer to William over into the NPC array of pointers.

    Yeah, that's kind of what I was leaning towards, though I was thinking of using IDs instead of pointers. Is one necessarily better than the other?

    Sir Carcass on
  • CelestialBadgerCelestialBadger Registered User regular
    edited February 2010
    Yeah, that's kind of what I was leaning towards, though I was thinking of using IDs instead of pointers. Is one necessarily better than the other?

    Depends on the circumstance.

    CelestialBadger on
Sign In or Register to comment.