CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 14 of 14
  1. #1
    Join Date
    Feb 2009
    Location
    USA
    Posts
    68

    Too many pass by reference functions??

    Hi, I am making a blackjack game. Well it is the 3rd one I have made. And i am using structures to simulate the cards, the deck, the players hand, and the players. My "past" BJ programs did not use structures, instead i used Global Arrays to simulate the deck and players hands. The reason i used global arrays is because almost every function changes something about either the deck or the players hands. So instead of passing arrays as arguments I made them global and let everything have easy access to them.
    Now with the structures i am encountering the same issue. Almost every function needs direct access to the structures. So now i am using pass by reference in almost every function call. I was wondering if it is a bad idea to have so many pass by reference functions.

    Below are my Structures and the Function Prototypes

    Code:
    /* Card represents a playing card.
     */
    struct Card
    {
        Card() : value(0), visual("[X]"){} //Default Constructor
        int value;      //Face Value
        string visual;   //Visual Representation. [A],[4],[10]
    };
    
    /* Hand represents a Hand of Cards.
     */
    struct Hand
    {
        Hand() : value(0), count(0){}  //Default Constructor
        int value;        //Sum of FaceValue of all the cards in Hand.
        int count;        //The # of cards in the hand.
        Card cards[10];   //The actual cards in the hand.
    };
    
    /*Deck represents a Deck of Cards
     */
    struct Deck
    {
        Deck() : count(0),top(0){}  //Default Constructor
        int top;           //Holds the position of the card ontop.
        int count;         //The count of cards.
        Card cards[52];    //The actual cards in the deck.
    };
    
    /* Player acts as a blackjack player or dealer.
     */
    struct Player
    {
        Player() : money(1000), bustStatus(false),bet(0){}
        Hand hand;        //Players actual cards.
        int money;        //The players betting money
        int bet;          //The players actual bet.
        bool bustStatus;  //Indicating whether a player busts. true=bust
    };
    
    //Function Prototypes
    
    
    Deck createDeck();             
    void shuffle(Deck&);          
    Card getCard(Deck&);        
    
    void addCardToHand(Hand&,Card);     
    void clearHand(Hand&);                      
    
    void play(Deck&,Player&,Player&);               
    void playersTurn(Player&,Player&,Deck&);     
    void dealersTurn(Player&,Deck&);                
    void getBet(Player&);                                
    void determineWinner(Player&, Player&);      
    
    void printDeck(Deck);
    void printHand(Hand);                    
    void printTable(Player,Player);
    As you can see almost every function is Pass By Reference. Is this bad? or is it ok? I did not think the entire source was neccessary. I have the game finished and it works correctly as far as i can tell but i am not sure about all the references.Also, before anyone suggests using classes i am having some issues getting a simple class to work for me so i cannot implement that atm. Thanks for any comments or suggestions and etc.

    Gerald
    Last edited by g.eckert; March 14th, 2009 at 07:13 AM.

  2. #2
    Join Date
    Feb 2009
    Location
    India
    Posts
    444

    Re: Too many pass by reference functions??

    Passing references is fine and the right way to do it.
    If you will not be modifying the structure inside the function, you should consider using constant references.

    void shuffle(const Deck&)
    «_Superman
    I love work. It gives me something to do between weekends.

    Microsoft MVP (Visual C++)

  3. #3
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Too many pass by reference functions??

    You are still a long way from thinking like an object oriented developer. Until you change your mindset, you should probably not even think about writing actual code (it is impossible to write code if you dont know how to think about what you are writing.

    Objects have two things: State and Behaviour. Your current way of thinking has these completely separated.

    You need to think about the BEHAVIOURS of a card, a deck and a player. Write down each and every thing that these items DO, then these will help you to start thinking of the member functions to put in your structures.

    As it stands now, you design is a very "1980's" structured programming approach, and not an object oriented one at all.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  4. #4
    Join Date
    Feb 2009
    Location
    USA
    Posts
    68

    Re: Too many pass by reference functions??

    I had no idea structs could have functions. Someone said they were "just like classes" but i was under the impression they were "just like classes" without functions. XD. So you are saying i could make a struct like this.

    Code:
    struct Thing{
        thing() : value(0), title("X"){}
    
        int value;      //data Members
        char title;
    
        int getValue(){
            return value;
        }
    
        void setValue(int val){
            value=val;
        }
    
    };
    Not sure about the syntax of the above. I do understand the OOP concept, I am coming from Java and i was able to implement inheritence and polymorphism in that language. The struct thing is completely new to me and my C++ book has failed me again, no mention of methods inside a struct, in part my fault for not researching. As for my BlackJack game I wanted to use classes/objects for the Card, Deck, Hand, Player but I simply cannot get classes to work for me right now. Thats why i resorted to structs that would hold the data. I agree it is quite weird the way i have it setup, but my idea of structs was that they were somewhat limited, to only Holding data. Thanks for the info.

  5. #5
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Too many pass by reference functions??

    Quote Originally Posted by g.eckert View Post
    I had no idea structs could have functions. Someone said they were "just like classes" but i was under the impression they were "just like classes" without functions. XD. So you are saying i could make a struct like this.
    They are EXACTLY the same as classes except:

    1) Default inheritance is public for struct / private for class
    2) Default member visibility is public for struct / private for class

    If this is not 100% completely and firmly in your head, then you need to go back to the basics.

    C++ can NOT be learned in an ad-hoc manner. It requires a careful, organized course of study.

    If you have missed this point, then there are probably a few hundred (seriously!) other things that you "think" that are also completely wrong.

    It will take much more time to unlearn all of these items, since you have no clue which of your thoughts are correct and which are flawed.

    Please note that this is not a personal "slam" or "insult". This is the result of having spent the ast 30+ years teaching programming to people in various means.

    To get back on the "right path" usially takes months of dedicated effort, by forgetting everything you think you know then...

    1) Getting a good book. Real paper..not on-line.
    2) Read EVERY word
    3) Type in every piece of code (yes even the two liner, and even if there is a CD/DVD)
    4) Step through every line with the debugger, look at how all of the variables change as each line execute.
    5) Never proceed past the end of a chapter unless you are confident that you understand 100% of the presented material.
    6) Before proceeding to the next chapter, wtrite a program of your own that uses EVERYTHING that was taught in the chapter. Do this with the book closed. Step through every line of this program. When you think it is all good, then re-open the book and validate that you did not miss anything.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  6. #6
    Join Date
    Feb 2009
    Location
    USA
    Posts
    68

    Re: Too many pass by reference functions??

    Ok, yea i understand your comments are not an insult. They seem rather "rough". It is funny you say not to skip ahead or learn adhoc, because that is basically what i am doing. We are learing about loops, if statements, and functions in my C++ class and this would be the 3rd time i have been tought how a for loop executes. So i skip ahead and Ill admit i dont know anything about how a struct works internally because i am just testing them out to see what they do. Now im not so impatient to skip ahead and try using virtual functions or linked lists or templates in C++. Its not that im trying to learn topics that are above me I am just playing around and seeing what they do and seeing what is new, to me, in C++. I dont see a problem with looking ahead and trying "new" stuff out. And as you suggest at the bottom of your post I do thouroughly test myself with what i have learned previously. My teacher assigns 1 program for a test. I write that plus another one just for fun.

  7. #7
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Too many pass by reference functions??

    Quote Originally Posted by g.eckert View Post
    Ok, yea i understand your comments are not an insult. They seem rather "rough".
    Only because I am very serious in this particular topic.

    I dont see a problem with looking ahead and trying "new" stuff out.
    Consider learning you to parachute jump. Jumping ahead (pun intended) without learning how to put on the pack, or pull the cord is a "problem".

    Well written material assumes that you are following in order and have 100% knowledge of everything that came before. If you skip even one sentance, your entire understanding may be incorrect.

    This is why "learning" from the Web is so bad of an experience for 99.9% of the people. The material is not organized, and you never know what information the material is assuming you already know. Even worse is that an estimated 85% of technical information on the web is incorrect.

    You can (at most geographic locations) prove this to yourself.

    1) Go to a bookstore, and pick up a book on C++ that you have never opened before.

    2) Open up the index and pick a topic that you think you know, then turn to the chapter immediately preceeding the chapter covering the material you picked.

    3) Read that chapter carefully.

    If you have a single "I didn't know that...", or "really, you can do that..." type of thought, then you have just proven that you have holes in your learnin experience.

    As a result when you are using the topic material that you picked, it is highly likely that you will NOT write the program properly.

    Part of what my company does these days is technical screening for job applicants for clients. These positions can range from entry to senior level. At the low to mid range, I can pick out (with 90%+ accuracy) people who carefully studied books (one book at a time and in order), from people who jumped around and used an ad-hoc approach. The vast majority of the time, the former will land the job, and the latter will fail on the screening exams.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  8. #8
    Join Date
    Feb 2009
    Location
    USA
    Posts
    68

    Re: Too many pass by reference functions??

    Your example is completly valid and i see where the "problem" arises when you compare it to programming. But , just because i used structs to make my BlackJack game doesnt mean that i am prepared to use them in an "offical" manner. I also wouldnt say that i am familiar with or know how they work. Again its not that i am trying to Learn subjects ahead of me I am simply seeing what there is. In the future when i eventually learn about a subject, that i previously looked/played with, i dont assume that i was using it correctly before. All i know, is that i played around with it. Even the "Hello World" program everyone writes. You use
    cout<<"Hello World"<<endl;
    They have no idea what ( cout, <<,"",endl, ; ) mean or what they do. Yes they used the syntax and it worked but i doubt anyone knows what " cout "does. Then when I/O objects are taught they understand what it does. Thats not a great example but it is kind of what i am doing. Now dont get me wrong I completely understand what you are saying, but i cannot help but to look ahead and see what there is.

  9. #9
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Too many pass by reference functions??

    I wish you the best of luck (that is an honest well wish), I only hope you do not have too many late nights "pulling your hair out" and finding out "I wish I knew that before..."

    As far as:
    They have no idea what ( cout, <<,"",endl, ; ) mean or what they do.
    Then they have not been following any course, book, or other form of instruction that I would recommend. As a general rule, approaches which focus on the primitives before giving the user a good understanding of how to use the more abstract (higher level) functionallity of STL is obsolete, and should have died nearly a decade ago.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  10. #10
    Join Date
    Feb 2009
    Location
    USA
    Posts
    68

    Re: Too many pass by reference functions??

    Well thanks. As for having longs nights, I am sure I will have just as many as everyone else when trying to solve a problem. Not due to my lack of knowledge on a subject because if I were implement something I would be sure that I have a solid understanding before ever attempting to use it in a serious manner. I would not use for loops in my final project if i wasnt sure how they worked. Cheers.
    Google is your friend.

  11. #11
    Join Date
    Jan 2008
    Location
    California, USA
    Posts
    822

    Re: Too many pass by reference functions??

    If I may add and if it helps you,
    consider the following two classes
    Code:
    class CardA
    {
        public:
            CardA() : value(1) {}
            
            int getValue() const { return value; }
        
        private:
            int value;
    };
    
    class CardB
    {
        public:
            CardB() : value(1) {}
            void showValue() const { cout << value << endl; }
        
        private:
            int value;
    };
    When you compare these two classes,
    they both reveal their value in some way.
    The hard part is to decide which design is better?
    I personally think design A is more suitable in this case
    because a poker card itself doesn't "behave",
    but rather it has a "state" that can be manipulated as a behavior.
    I just thought this was something you might want to think about for your BJ game.

    bye~

  12. #12
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Too many pass by reference functions??

    Quote Originally Posted by potatoCode View Post
    I personally think design A is more suitable in this case
    because a poker card itself doesn't "behave",
    but rather it has a "state" that can be manipulated as a behavior.
    I just thought this was something you might want to think about for your BJ game.
    Exactly!!!! Plus, think of what happens when you want to use the Card class in a WinForms or ASP.Net application By referencing "cout" you have added a constraint on the usage of the class that is completely inappropriate....

    Much more interesting is handling the "Deck". Novice programmers will often implement "void Deck::Shuffle()" or "Card &Deck::TakeCard()". Both of these are incorrect. A deck does NOT shuffle itself, nor does it magically pop-off a card!!!!
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

  13. #13
    Join Date
    Jan 2008
    Location
    California, USA
    Posts
    822

    Re: Too many pass by reference functions??

    Master!
    I still haven't descended the mountain yet!
    When's the next pebble-snatching going to be!
    *shwooosh* <-- that's the sonicboom coming from my hand!

  14. #14
    Join Date
    Mar 2002
    Location
    St. Petersburg, Florida, USA
    Posts
    12,125

    Re: Too many pass by reference functions??

    Quote Originally Posted by potatoCode View Post
    Master!
    I still haven't descended the mountain yet!
    When's the next pebble-snatching going to be!
    *shwooosh* <-- that's the sonicboom coming from my hand!
    Yet these conceptual topics are what really needs to be taught and understood before the person ever writes their first line of code, regardless of language. (At least that is my opinion, and basted on a few decades of history).

    For some reason, people seem to think that programming is different than any other complex discipline. Imagine if people tried to perform heart surgery without every having been taught the fundamentals of anatomy.

    ps; My hand was actualy empty, with just the illusion of a pebble in your mind...you still have much to learn.
    TheCPUWizard is a registered trademark, all rights reserved. (If this post was helpful, please RATE it!)
    2008, 2009,2010
    In theory, there is no difference between theory and practice; in practice there is.

    * Join the fight, refuse to respond to posts that contain code outside of [code] ... [/code] tags. See here for instructions
    * How NOT to post a question here
    * Of course you read this carefully before you posted
    * Need homework help? Read this first

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured