Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. Problem with const struct initialization in a class

Problem with const struct initialization in a class

Scheduled Pinned Locked Moved C / C++ / MFC
questionc++helpannouncement
7 Posts 5 Posters 11 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • M Offline
    M Offline
    Marco Bertschi
    wrote on last edited by
    #1

    Alright, I've been bugging with this one for quite a while now. I have a struct which is const and part of a class and therefore I need to initialize it. What I have done so far:

    /****************************************************************************
    File: Boundaries.h
    Desciption: Contains boundary structs for different data types.
    Version: 1.0
    Author: MAB
    ****************************************************************************/
    #ifndef BOUNDARIES_H
    #define BOUNDARIES_H

    typedef struct{
    char upper;
    char lower;
    } charBoundary; //!< Boundary struct for char data types

    #endif //BOUNDARIES_H

    /****************************************************************************
    File: foo.h
    Desciption: Test class for Boundaries.h
    Version: 1.0
    Author: MAB
    ****************************************************************************/
    #ifndef FOO
    #define FOO

    using namespace std;
    #include <iostream> //!< Used for console output

    class foo{
    private:
    const charBoundary versionBoundary = {
    1,
    -5
    };
    public:
    };

    Now I recognized that the initialization

    const charBoundary versionBoundary = {
    1,
    -5
    };

    is only valid in C++11 - All compilers not supporting C++11 will choke on these lines. Now I come to the question I want to ask: Is there any other way to get it compilable to older compilers than making versionBoundary static or non-const or adding a constructor to the charBoundary struct? I do not like neither of the above mentioned possibilities but if there is no other solution - What would you recommend? Thanks in Advance PP

    You know the world is going crazy when the best rapper is a white guy, the best golfer is a black guy, the tallest guy in the NBA is Chinese, the Swiss hold the America's Cup, France is accusing the U.S. of arrogance, Germany doesn't want to go to war, and the three most powerful men in America are named "Bush", "Dick", and "Colon."

    D K E S 4 Replies Last reply
    0
    • M Marco Bertschi

      Alright, I've been bugging with this one for quite a while now. I have a struct which is const and part of a class and therefore I need to initialize it. What I have done so far:

      /****************************************************************************
      File: Boundaries.h
      Desciption: Contains boundary structs for different data types.
      Version: 1.0
      Author: MAB
      ****************************************************************************/
      #ifndef BOUNDARIES_H
      #define BOUNDARIES_H

      typedef struct{
      char upper;
      char lower;
      } charBoundary; //!< Boundary struct for char data types

      #endif //BOUNDARIES_H

      /****************************************************************************
      File: foo.h
      Desciption: Test class for Boundaries.h
      Version: 1.0
      Author: MAB
      ****************************************************************************/
      #ifndef FOO
      #define FOO

      using namespace std;
      #include <iostream> //!< Used for console output

      class foo{
      private:
      const charBoundary versionBoundary = {
      1,
      -5
      };
      public:
      };

      Now I recognized that the initialization

      const charBoundary versionBoundary = {
      1,
      -5
      };

      is only valid in C++11 - All compilers not supporting C++11 will choke on these lines. Now I come to the question I want to ask: Is there any other way to get it compilable to older compilers than making versionBoundary static or non-const or adding a constructor to the charBoundary struct? I do not like neither of the above mentioned possibilities but if there is no other solution - What would you recommend? Thanks in Advance PP

      You know the world is going crazy when the best rapper is a white guy, the best golfer is a black guy, the tallest guy in the NBA is Chinese, the Swiss hold the America's Cup, France is accusing the U.S. of arrogance, Germany doesn't want to go to war, and the three most powerful men in America are named "Bush", "Dick", and "Colon."

      D Offline
      D Offline
      David Crow
      wrote on last edited by
      #2

      Does it have to be const?

      "One man's wage rise is another man's price increase." - Harold Wilson

      "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

      "Show me a community that obeys the Ten Commandments and I'll show you a less crowded prison system." - Anonymous

      M 1 Reply Last reply
      0
      • D David Crow

        Does it have to be const?

        "One man's wage rise is another man's price increase." - Harold Wilson

        "Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons

        "Show me a community that obeys the Ten Commandments and I'll show you a less crowded prison system." - Anonymous

        M Offline
        M Offline
        Marco Bertschi
        wrote on last edited by
        #3

        Yep, thats why I ask - Without the const it would be easy, also if I'd make it static const. But for the purpose I need it const only would be the best solution.

        You know the world is going crazy when the best rapper is a white guy, the best golfer is a black guy, the tallest guy in the NBA is Chinese, the Swiss hold the America's Cup, France is accusing the U.S. of arrogance, Germany doesn't want to go to war, and the three most powerful men in America are named "Bush", "Dick", and "Colon."

        1 Reply Last reply
        0
        • M Marco Bertschi

          Alright, I've been bugging with this one for quite a while now. I have a struct which is const and part of a class and therefore I need to initialize it. What I have done so far:

          /****************************************************************************
          File: Boundaries.h
          Desciption: Contains boundary structs for different data types.
          Version: 1.0
          Author: MAB
          ****************************************************************************/
          #ifndef BOUNDARIES_H
          #define BOUNDARIES_H

          typedef struct{
          char upper;
          char lower;
          } charBoundary; //!< Boundary struct for char data types

          #endif //BOUNDARIES_H

          /****************************************************************************
          File: foo.h
          Desciption: Test class for Boundaries.h
          Version: 1.0
          Author: MAB
          ****************************************************************************/
          #ifndef FOO
          #define FOO

          using namespace std;
          #include <iostream> //!< Used for console output

          class foo{
          private:
          const charBoundary versionBoundary = {
          1,
          -5
          };
          public:
          };

          Now I recognized that the initialization

          const charBoundary versionBoundary = {
          1,
          -5
          };

          is only valid in C++11 - All compilers not supporting C++11 will choke on these lines. Now I come to the question I want to ask: Is there any other way to get it compilable to older compilers than making versionBoundary static or non-const or adding a constructor to the charBoundary struct? I do not like neither of the above mentioned possibilities but if there is no other solution - What would you recommend? Thanks in Advance PP

          You know the world is going crazy when the best rapper is a white guy, the best golfer is a black guy, the tallest guy in the NBA is Chinese, the Swiss hold the America's Cup, France is accusing the U.S. of arrogance, Germany doesn't want to go to war, and the three most powerful men in America are named "Bush", "Dick", and "Colon."

          K Offline
          K Offline
          Kosta Cherry
          wrote on last edited by
          #4

          OK, this is not the most elegant solution, but here we go:

          charBoundary getInitialBoundary()
          {
          charBoundary c ={2,-5};
          return c;
          }

          class foo{
          public:
          foo() : versionBoundary(getInitialBoundary()) {}
          private:
          const charBoundary versionBoundary;
          };

          1 Reply Last reply
          0
          • M Marco Bertschi

            Alright, I've been bugging with this one for quite a while now. I have a struct which is const and part of a class and therefore I need to initialize it. What I have done so far:

            /****************************************************************************
            File: Boundaries.h
            Desciption: Contains boundary structs for different data types.
            Version: 1.0
            Author: MAB
            ****************************************************************************/
            #ifndef BOUNDARIES_H
            #define BOUNDARIES_H

            typedef struct{
            char upper;
            char lower;
            } charBoundary; //!< Boundary struct for char data types

            #endif //BOUNDARIES_H

            /****************************************************************************
            File: foo.h
            Desciption: Test class for Boundaries.h
            Version: 1.0
            Author: MAB
            ****************************************************************************/
            #ifndef FOO
            #define FOO

            using namespace std;
            #include <iostream> //!< Used for console output

            class foo{
            private:
            const charBoundary versionBoundary = {
            1,
            -5
            };
            public:
            };

            Now I recognized that the initialization

            const charBoundary versionBoundary = {
            1,
            -5
            };

            is only valid in C++11 - All compilers not supporting C++11 will choke on these lines. Now I come to the question I want to ask: Is there any other way to get it compilable to older compilers than making versionBoundary static or non-const or adding a constructor to the charBoundary struct? I do not like neither of the above mentioned possibilities but if there is no other solution - What would you recommend? Thanks in Advance PP

            You know the world is going crazy when the best rapper is a white guy, the best golfer is a black guy, the tallest guy in the NBA is Chinese, the Swiss hold the America's Cup, France is accusing the U.S. of arrogance, Germany doesn't want to go to war, and the three most powerful men in America are named "Bush", "Dick", and "Colon."

            E Offline
            E Offline
            Erudite_Eric
            wrote on last edited by
            #5

            Dont you have to do the initialisation in the class constructor? I am not a C++ expert, I have used it enough, but it seems as if it should go there. If not and you only need one instance of the struct shared among all instances of the clas you can make it static. (Again, not an expert here, but I seem to recall from the dregs f my memoery that this is the case, please correct me anyone if it is not so).

            M 1 Reply Last reply
            0
            • E Erudite_Eric

              Dont you have to do the initialisation in the class constructor? I am not a C++ expert, I have used it enough, but it seems as if it should go there. If not and you only need one instance of the struct shared among all instances of the clas you can make it static. (Again, not an expert here, but I seem to recall from the dregs f my memoery that this is the case, please correct me anyone if it is not so).

              M Offline
              M Offline
              Marco Bertschi
              wrote on last edited by
              #6

              This is actually a bit of research for an article of mine (If you want to peek into it, have a glance here: Don't mess up your #defines[^]).

              Erudite_Eric wrote:

              Dont you have to do the initialisation in the class constructor?

              I initially did this, but as stated in the article the problem is that you'd be able to change the struct's value after the object initialization which could lead to an unexpected behavior of your program. On the other side, making it static const leads to the fact that every instance shares the same instance of the struct, which is possible and would not lead to any unexpected behavior. I am still searching for a solution which would make it only const, just for design reasons. Thanks for your post anyways, ŷou brought me onto the track of a false thinking of mine - I refused the static const because I thought I'd have to address the struct as foo::struct which is not the case. Gotta update that article...

              You know the world is going crazy when the best rapper is a white guy, the best golfer is a black guy, the tallest guy in the NBA is Chinese, the Swiss hold the America's Cup, France is accusing the U.S. of arrogance, Germany doesn't want to go to war, and the three most powerful men in America are named "Bush", "Dick", and "Colon."

              1 Reply Last reply
              0
              • M Marco Bertschi

                Alright, I've been bugging with this one for quite a while now. I have a struct which is const and part of a class and therefore I need to initialize it. What I have done so far:

                /****************************************************************************
                File: Boundaries.h
                Desciption: Contains boundary structs for different data types.
                Version: 1.0
                Author: MAB
                ****************************************************************************/
                #ifndef BOUNDARIES_H
                #define BOUNDARIES_H

                typedef struct{
                char upper;
                char lower;
                } charBoundary; //!< Boundary struct for char data types

                #endif //BOUNDARIES_H

                /****************************************************************************
                File: foo.h
                Desciption: Test class for Boundaries.h
                Version: 1.0
                Author: MAB
                ****************************************************************************/
                #ifndef FOO
                #define FOO

                using namespace std;
                #include <iostream> //!< Used for console output

                class foo{
                private:
                const charBoundary versionBoundary = {
                1,
                -5
                };
                public:
                };

                Now I recognized that the initialization

                const charBoundary versionBoundary = {
                1,
                -5
                };

                is only valid in C++11 - All compilers not supporting C++11 will choke on these lines. Now I come to the question I want to ask: Is there any other way to get it compilable to older compilers than making versionBoundary static or non-const or adding a constructor to the charBoundary struct? I do not like neither of the above mentioned possibilities but if there is no other solution - What would you recommend? Thanks in Advance PP

                You know the world is going crazy when the best rapper is a white guy, the best golfer is a black guy, the tallest guy in the NBA is Chinese, the Swiss hold the America's Cup, France is accusing the U.S. of arrogance, Germany doesn't want to go to war, and the three most powerful men in America are named "Bush", "Dick", and "Colon."

                S Offline
                S Offline
                Stefan_Lang
                wrote on last edited by
                #7

                There are many solutions for your problem if you don't insist on trying to initialize a struct. 1. Write a function. Apparently your purpose is to check a value range, so all you really need is a function:

                /**
                * check if a given value is within the range
                * @return -1 if the value is too low, 0 if the value is in range, 1 if the value is too high
                * @param value the value you want to check
                */
                int inVersionRange(char value);

                That's all you need in a header. The implementation file then can contain the actual constants:

                const char Min_Version = -5;
                const char max_version = 1;

                int inVersionRange(char value) {
                int result = 0;
                if (value < Min_Version)
                result = -1;
                if (value > Max_Version)
                result = 1;
                return result;
                }

                If you need more functions that access these boundaries, put the implementation into the same file. 2. static const

                struct VersionRange {
                static const char VMIN;
                static const char VMAX;
                };
                // initialize in implementation file like this:
                const char VersionRange::VMIN = -5;
                const char VersionRange::VMAX = 1;

                3. define the values within a namespace instead of a struct (same as above, but you don't need the static keyword) 4. create a singleton class to hold the constants and make them write-only Similar to 2, but you create an instance of your class (or struct) which is made 'static constant' through programming concepts rather than language keywords. 5. use const references and an array intializer This comes back to your original idea of using an initializer:

                // header file
                class VersionBoundary {
                static const char* const boundaries;
                public:
                static const char& VMIN;
                static const char& VMAX;
                }
                // implementation file
                const char* const VersionBoundary::boundaries = { -5, 1 };
                const char& VersionBoundary::VMIN = *(boundaries+0); // reference to first value
                const char& VersionBoundary::VMAX = *(boundaries+1); // reference to second value

                1 Reply Last reply
                0
                Reply
                • Reply as topic
                Log in to reply
                • Oldest to Newest
                • Newest to Oldest
                • Most Votes


                • Login

                • Don't have an account? Register

                • Login or register to search.
                • First post
                  Last post
                0
                • Categories
                • Recent
                • Tags
                • Popular
                • World
                • Users
                • Groups