CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 11 of 11
  1. #1
    Join Date
    May 2007
    Posts
    8

    Consts for use in classes

    Hello folks,

    I'm something of a newb to C++, and I've been trying to program a simple Tetris-like game. In doing so, I've run into a situation that seems to bother me frequently, so I thought I'd finally seek some advice about it. Forgive me if my question seems ignorant, or if this is not the right forum for it.

    My basic question is: where and how, ideally, should I declare and define consts that are to be used by a class? Should they be declared within the class itself, or just in the same header file as it? In either case, I'm not exactly sure what method would be ideal.

    For example, in my Tetris game, I have a "Block" class. The size of all Blocks is constant and needs to be known by methods within the Block class. Should I express this as:

    Code:
    // Block.h
    
    const int BLOCK_SIZE = 32;
    
    class Block
    {
    public:
        void doSomethingInvolvingKnowledgeOfBLOCK_SIZE();
        // blah blah
    };
    This seems somehow less than optimal to me. For one thing, I've been told that header files shouldn't allocate any memory, and the definition of a const does (as far as I know). For another thing, BLOCK_SIZE can be used by client-type folks without so much as an acknowledgement that it's associated with the Block class. That's bad, right?

    So, as an alternative, should I do something like this?

    Code:
    // Block.h
    
    class Block
    {
    public:
        Block();
        void doSomethingInvolvingKnowledgeOfBLOCK_SIZE();
    private:
        static const int BLOCK_SIZE;
        // blah blah
    };
    My instincts tell me that that is better. Is it? Is that even syntactically correct?--again, forgive my newbishness. My understanding is that the const then has to be initialized via a constructor's initialization list. Is this correct, and if so, doesn't it potentially force me to duplicate the value of the constant, if multiple Block constructors were to exist?

    Please don't chew me apart; I know some of this could be determined via trial and error, but I'd rather hear it from the masters, especially as this is chiefly an issue of design and not of syntax. What should I be doing in cases like this? Again, where and how should the const be declared and defined?

    Any advice is greatly appreciated.

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

    Re: Consts for use in classes

    Please don't chew me apart;
    Fresh Meat...Yummmmm...

    Seriously, welcome to CG, and your post is in the right area (and you even used c ode tags )

    Just think "encapsulation". If the constant is a value that makes sense specifically in the context of the class, then it should be a static member (visibility [private,protected,public] dependant on usage), so your second example is proper.

    Just remember that in a .cpp file your will need:
    Code:
        
    static const int block::BLOCK_SIZE = 123;
    An alternative (which also gives the compiler some good optimization capabilities is to use Enums rather than constants:
    Code:
    class Block
    {
    public:
       enum ClassConstants
          {
             BLOCK_SIZE = 123;
             SILLY_NUMBER = 456;
          }
    This is especially good if there are related constants (where you would pick one of a limited set of values:

    Code:
    class Block
    {
    public:
       enum BitsPerPixels     
    {
             Bits_8 = 8,
             Bits_16 = 16,
             Bits_24 = 24,
             Bits_32 = 32
    }
    Because now you can write your methods with some better constraints
    Code:
        void SetDepth(BitsPerPixels  bitsPerPixel)
    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

  3. #3
    Join Date
    May 2007
    Posts
    8

    Re: Consts for use in classes

    Thank you so much for the prompt, friendly reply. That clears things up a great deal.

    I have another, more trivial question. Suppose that people who aren't Blocks need to know what BLOCK_SIZE is. In that case, should I keep to the standard data-hiding philosophies, and make it accessible only via some static "GetBlockSize" method? Or, BLOCK_SIZE being constant, is it a better idea just to make it a public member?

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

    Re: Consts for use in classes

    Quote Originally Posted by keriostar
    Thank you so much for the prompt, friendly reply. That clears things up a great deal.

    I have another, more trivial question. Suppose that people who aren't Blocks need to know what BLOCK_SIZE is. In that case, should I keep to the standard data-hiding philosophies, and make it accessible only via some static "GetBlockSize" method? Or, BLOCK_SIZE being constant, is it a better idea just to make it a public member?
    That is a matter of debate. Personally for static constant values, I expose them directly in most cases. The exception would be if you want to be able to track who is reading the value, in this case you want to expose it via a GetMethod() or a property.

    For non-const items, I always implent the data elements as private (95%) or protected (5%), NEVER public.

    [This is the non-Visual C++ forum, so check your specific compiler to see if it (and any others you might want to port to) support property syntax.
    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

  5. #5
    Join Date
    May 2007
    Posts
    8

    Re: Consts for use in classes

    Excellent. Thanks again, CPUWizard--you've been a great help.

  6. #6
    Join Date
    Aug 2000
    Location
    New York, NY, USA
    Posts
    5,656

    Re: Consts for use in classes

    Quote Originally Posted by TheCPUWizard
    Just remember that in a .cpp file your will need:
    Code:
        
    static const int block::BLOCK_SIZE = 123;
    Or you could initialize that static const IN the class:
    Code:
    class A
    {
    public:
          static const int s_nBlockSize = 42;
    };
    Vlad - MS MVP [2007 - 2012] - www.FeinSoftware.com
    Convenience and productivity tools for Microsoft Visual Studio:
    FeinWindows - replacement windows manager for Visual Studio, and more...

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

    Re: Consts for use in classes

    Quote Originally Posted by VladimirF
    Or you could initialize that static const IN the class:
    Code:
    class A
    {
    public:
          static const int s_nBlockSize = 42;
    };
    Vladimir,

    I have had some problems with that in the past (older compilers), and have not tried it recently, but is there not a potential for...
    Code:
    const int * p1 = &bBlock::s_nBlockSize;  // in file1.cpp
    
    const int * p2 = &bBlock::s_nBlockSize;  // in file2.cpp
    
    Finally...
    
    if (p1 == p2) // Comparing pointer values, not values of the target....
    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
    Aug 2000
    Location
    New York, NY, USA
    Posts
    5,656

    Re: Consts for use in classes

    Quote Originally Posted by TheCPUWizard
    I have had some problems with that in the past (older compilers), and have not tried it recently, but is there not a potential for...
    Can't imagine why there would be...
    Also, can't see what will be the difference between our code fragments.
    Vlad.
    P.S. What do you mean by "older"?
    Vlad - MS MVP [2007 - 2012] - www.FeinSoftware.com
    Convenience and productivity tools for Microsoft Visual Studio:
    FeinWindows - replacement windows manager for Visual Studio, and more...

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

    Re: Consts for use in classes

    Quote Originally Posted by VladimirF
    Can't imagine why there would be...
    Also, can't see what will be the difference between our code fragments.
    Vlad.
    P.S. What do you mean by "older"?
    Ohhhh.. Back around 5-7 years ago, WatCom IIRC...

    The problem was that for static POD constants initialized in the header, no memory was actually allocated and the value used as a literal, unless the address of the constant was taken. Then a memory location had to be assigned. Unfortunately it was often implemented as a file scope constant. This would yield an identical copy in each of the compilation units which contained an address refference. Effectively yielding....

    Code:
    //file1.cpp
    static const int nBlockSize = 123;
    const int * p1 = &s_nBlockSize;  // in file1.cpp
    
    //file2.cpp
    static const int nBlockSize = 123;
    const int * p2 = &s_nBlockSize;  // in file2.cpp
    And this would (obviously) yield different pointer values....
    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
    Aug 2000
    Location
    New York, NY, USA
    Posts
    5,656

    Re: Consts for use in classes

    Quote Originally Posted by TheCPUWizard
    Ohhhh.. Back around 5-7 years ago, WatCom IIRC...
    That's BAD! Never had a pleasure to use Watcom...

    So, it's not only Microsoft who doesn't follow standards?
    Vlad - MS MVP [2007 - 2012] - www.FeinSoftware.com
    Convenience and productivity tools for Microsoft Visual Studio:
    FeinWindows - replacement windows manager for Visual Studio, and more...

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

    Re: Consts for use in classes

    Quote Originally Posted by VladimirF
    That's BAD! Never had a pleasure to use Watcom...

    So, it's not only Microsoft who doesn't follow standards?
    Actually standards compliance has often been an issue (although less so with C++ in recent years). I can wait to the "C++ 0x" standard starts being "supporteD" by compilers, I am sure the first few iterations will be "interesting"
    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

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