Thread: how to declare constant strings in a class?

  1. #1
    Registered User
    Join Date
    Aug 2008
    Posts
    188

    how to declare constant strings in a class?

    hi, in C#, the syntax is this:
    Code:
    public static class SomeStrings {
      public const string A = "A";
      public const string B = "B";
    }
    so i reference these constant strings with SomeStrings.A etc.

    how do i do the same thing in c++, like SomeString::A? thanks.

  2. #2
    Registered User
    Join Date
    Jan 2005
    Posts
    7,366
    It sounds like you want a static const member.
    Code:
    // Declare in class inside the header file:
    class SomeStrings
    {
    public:
        static const std::string A;
        static const std::string B;
    };
    Code:
    // Define in a source file:
    const std::string SomeStrings::A = "A";
    const std::string SomeStrings::B = "B";
    Code:
    // Example of using the strings somewhere else:
    {
        std::cout << SomeStrings::A << ',' << SomeStrings::B << '\n';
    }
    Note that if your class is just storing const strings, you can use a namespace instead of a class. Also note that the example shows strings that are the same across all instances of the class. If you want strings that are const but can be initialized differently by different instances, then you don't want static and you have to use the initializer list to initialize them.
    Last edited by Daved; 08-11-2008 at 02:02 PM.

  3. #3
    Registered User
    Join Date
    Aug 2008
    Posts
    188
    ah...the source file!

    gets me every time

    thanks.

  4. #4
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    An optional but ugly alternative is to make your string's mutable in the class. This allows const functions to alter the string. However this can be abused. One could say that your strings are not const if you need to alter them so why declare them as const or mutable? However there are some rare circumstances where mutable is a good choice. If you find yourself using mutable in a lot of places there is a good chance you are abusing it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Initializing constant object member of a class
    By Canadian0469 in forum C++ Programming
    Replies: 3
    Last Post: 12-03-2008, 08:05 PM
  2. deriving classes
    By l2u in forum C++ Programming
    Replies: 12
    Last Post: 01-15-2007, 05:01 PM
  3. Replies: 7
    Last Post: 05-26-2005, 10:48 AM
  4. structure vs class
    By sana in forum C++ Programming
    Replies: 13
    Last Post: 12-02-2002, 07:18 AM
  5. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM