struct with const member variable without explicit constructor

  • Permalink
  • submit to reddit
  • Email
  • Follow


Hi.

Is the following code c++:

   typedef struct {
       int a;
       int const b;
   } C;

The Intel compiler gives the following warning message:
warning #411: class "C" defines no constructor to initialize the
following:

             const member "C::b"

But it is possible to initialize b with the old C-style:

C c = { 1, 2 };


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply chb 2/2/2011 7:39:18 AM

See related articles to this posting


On 2011-02-02 14:39, chb wrote:
> 
> Is the following code c++:
> 
>    typedef struct {
>        int a;
>        int const b;
>    } C;

Yes, this is well-formed C++.

> The Intel compiler gives the following warning message:
> warning #411: class "C" defines no constructor to initialize the
> following:
> 
>              const member "C::b"
> 
> But it is possible to initialize b with the old C-style:
> 
> C c = { 1, 2 };

Your example is reasonable but note that compilers are free to
diagnose anything - even well-formed and well-defined code.

HTH & Greetings from Bremen,

Daniel Kr�gler


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply ISO 2/2/2011 4:12:20 PM

On 02/02/2011 13:39, chb wrote:
> 
> Hi.
> 
> Is the following code c++:
> 
>    typedef struct {
>        int a;
>        int const b;
>    } C;
> 
> The Intel compiler gives the following warning message:
> warning #411: class "C" defines no constructor to initialize the
> following:
> 
>              const member "C::b"
> 
> But it is possible to initialize b with the old C-style:
> 
> C c = { 1, 2 };
> 
> 
Which is why it is a warning and not an error.


-- 
      [ See http://www.gotw.ca/resources/clcm.htm for info about ]
      [ comp.lang.c++.moderated.    First time posters: Do this! ]

0
Reply Francis 2/2/2011 4:13:24 PM
comp.lang.c++.moderated 10665 articles. 10 followers. Post

2 Replies
1159 Views

Similar Articles

[PageSpeed] 25


  • Permalink
  • submit to reddit
  • Email
  • Follow


Reply:

Similar Artilces:

Pointer to a member variable in a struct without dereferencing the member
All, I have the below struct and I need to access the pointer to the "void * data" member without actually dereferencing the member variable. I could have gone with the approach of (ptr + sizeof(int) *4), but I dislike this idea - if I change something in the structure, I would have to revisit this part as well. struct something { int size; int msglen; int count; int handle; void *data; }; struct something *ptr = (struct something *) msg; char *data_ptr = ptr + sizeof(int) * 4; -- comp.lang.c.moderated - moderation address: clcm@plethora.n...

Virtual inheritance and constructors in base classes with const member variables
Hi, I have a question, in a "dreaded diamond" situation, regarding the following code: ---- Begin code #include <iostream> using namespace std; template <int n> class Animal { protected: int extremities_; const int flag_; public: Animal(const int &numext) : extremities_(numext), flag_(1) {cout << numext << " Extrms\n";} Animal() {cout << "A NoArgs\n";} // Breaks things // Animal() : flag_(0) // {cout << "A NoArgs\n";} // Uncomment to fix code }; template <int n> class ...

Help on warning: non-static const member in class without a constructor
Following warnings are found in my application: ..../adm_std_mo_descr.h:240: warning: non-static const member `const struct std_tee_t std_mo::tee' in class without a constructor ..../adm_std_mo_descr.h:244: warning: non-static const member `const char *const std_mo::name' in class without a constructor The header file looks as the following: typedef struct std_tee { const unsigned int size; } std_tee_t; typedef struct std_mo { const std_tee_t tee; const char* const name; } std_mo_t; I am wondering what the problem is. I tried to write a small test program, but it c...

Why you should never use a const& parameter to initialize a const& member variable!
myFAQ 0815 - Why you should never use a const& parameter to initialize a const& member variable! Today, once again, I shot myself in the foot. I thought I'd share this. Rule: You must never use a const-reference parameter to a constructor to initialize a const-reference member-variable. Reason: const& parameters bind to temporaries. You do not want to track temporaries! Solution: Use a const* parameter If you want a const& member variable in a class to reference something, then it has to be initialized in the ctor. But you must not use a const& paramet...

assign a struct variable into another struct variable
Hi, I would appreciate if someone could tell me what I'm doing wrong ? #include<iostream> using namepace std ; struct person{ char *firstname ; int age ; } ; struct person1{ char *firstname ; int age ; } ; int main(int argc, char *argv[]) { person me ; person1 me1 ; me.firstname = "me" ; me.age = 150 ; me1 = me ; // here's where the problem occurrs..... *The Error Report I Get* (structs.cpp: in function 'int main()': structs.cpp:22: error: no match for 'operator=' in 'me1 = me' structs.c...

const struct members
Suppose I have a structure with many members, and I pass a pointer to that structure to a function. I'd like the prototype of the function to specify that it will only be changing certain members of the function, but I have only the following horrific way to do that. Can someone please suggest a better alternative? #include <stdio.h> struct foo { char *a; char *b; }; struct const_foo { const char *a; const char *b; }; struct foo_const_a { const char *a; char *b; }; struct foo_const_b { char *a; const char *b; }; void modify_a(struct foo_const_b...

pointer to a member of a struct which is in turn a member of an array of structs
Hi folks -- I have a 4-long array t[ ] of of struct Targets. And a table of int * in p[ ]. I need to set up the int * entries in p[ ] such that each can reference an int in any member of the Targets t[ ] array. How to do it? Much-simplified example: 1. #include <stdio.h> 2. int main(int argc, char* argv[ ]) { 3. int ix; 4. typedef struct { int num1; int num2; int num3; } Targets; 5. Targets t[4]; 6. 7. typedef struct { int *number; } Pointers; 8. Pointers *ap; 9. Pointers p[3] = { { &t[?].num1 }, 10. ...

const structs in other structs
I think the following code should give an error when compiled, however, the compiler I am using doesn't raise one. The code is: typedef struct { char a1; char a2; char a3; } A_T; typedef struct { char b1; const A_T ba; } B_T; B_T b; void main(void) { b.ba.a1 = 0; } Should this give an error? I've declared the A_T part of B_T as a const and then written to it in main(). I think it should, but my compiler is happy with it. Any comments will be appreciated. Thanks Chris chris.hauxwell@sevcon.com (Chris Hauxwell) wrote: >I think the following code sh...

explicit and not explicit constructors
Hi. I've .... class functor { .... functor(): implementation_(0) { } explicit functor ( int ): implementation_(0) { } explicit functor ( char * ): implementation_(0) { } template <typename functionType> functor(functionType function): implementation_(new implementation::handler<functor, functionType>(function)) { } ..... } and I've following code: void someFunction( int a = 0 ); void someFunction( functor<..> a = 0 ); calling of someFunction without parameters makes error "ambiguous call to overloaded function" because template constructo...

Put variables into member variables or function variables?
I modify my code into following sample code. CTest is a class only constructed once when the device power on. CTest::ExecuteRunState is a function entered periodically. Do you think whether it is necessary to put the local variables into class private members? Otherwise, each time entering the ExecuteRunState(), those local variables will be decleared and initionalized one time. It's a waste of cpu resource. class CTest { public: CTest(); ~CTest(); private: void CTest(const CTest & m_CTest); void ExecuteRunState(); //This function will entered periodically ...

Problems with const in member variables
I am having problems with const in member variables, or more specifically getting things working nicely. class Sample { public: Sample(int itemId); const int itemId; }; This is pretty straightforward. However, if I use add a copy constructor and operator = (not declared above, but assume the declaration) Sample::Sample(const Sample& rhs) { *this = rhs; }; // and of course Sample& Sample::operator=(const Sample& rhs) { if(this != & rhs) { itemId = rhs.itemId; } return * this; } Neither of these functions compiles of course. The copy constructor needs t...

Variable Sized Struct Members?
My understanding is that struct members will remain in order such that the following can be used to support variable sized members: struct indexed_values { int *values; unsigned char bitset[0]; }; struct meta_data { struct indexed_values foo; unsigned char _foo_bs[8]; struct indexed_values bar; unsigned char _bar_bs[16]; struct indexed_values zap; unsigned char _zap_bs[4]; .... }; In this case accessing meta_data->bar[15] for example cannot overlap with other members of runover into the zap member. Is this leg...

static member variables vs. static member function variables
Is there any reason to use the following: struct S { S(); }; class A { static S s; }; S myS = A::s; // usage when you can use the following instead? class A { static int& GetS() { static S s; return s; } }; S myS = A::GetS(); // usage The latter not only guarantees that the variable will be initialized before being used, but it also prevents the user from having to put a "A::S s" statement somewhere in a .cpp file. Is there something else I'm missing? --Terry [ See http://www.gotw.ca/resources/clcm.htm for info about ] ...

set structs const members
Hi, I am having problems with the following code: // mylib.h #define _CRT_SECURE_NO_WARNINGS #include <string> #include <vector> namespace mylib { struct reqline { const std::string method; const std::string uri; const std::string vprot; reqline(); reqline(std::string const & line); }; } // mylib.cpp #include "mylib.h" namespace mylib { // reqline reqline::reqline() : method(""), uri(""), vprot("") {} reqline::reqline(const std::string & line) { std::vector<std::string&g...

explicit conversion without a constructor
Hello all, I'm working on a 64 bits unsigned integer class for compilers that don't support long long. The idea is that depending on the compiler/options, I do: typedef TUInt64 KUInt64; or typedef unsigned long long KUInt64; (supposedly unsigned long long is 64 bits, I know it could be more according to C99). And I use KUInt64 everywhere in my code. I got everything working except when it's about converting KUInt64 to, say, some integer native type that I know is 32 bits unsigned (at most, unsigned long) typedefed to KUInt32. If I do: class TUInt64 { public: .... ...

Constructor
Hello everybody, I had this problem several times now and did not yet get the reasoning behind it. I have a class with a pointer as member variable, lets say a float array. Furthermore, I have two constructors of which the first is calling the second one... Here an easy example (so don't worry about the semantics ;) ) Member variables: float* pFeatVec; int dimension; FeatureVector::FeatureVector(ConfigReader* crd2) { pFeatVec = NULL; dimension = 4; FeatureVector(dimension); } FeatureVector::FeatureVector(int dim) { dimension = dim; pFeatVec = new float[dimension]; for(i...

const member variables in a class...
Hi Everyone, When a variable is declared as const, it is initialized along with the declaration, as modification later on is not possible. Having seen that, how about const variables in a class? Is it possible for a class to have const variables? As just declaring the class alone doesn't create any memory, only creation of objects results in memory allocation for the object. Thanks in advance!!! sam_cit@yahoo.co.in wrote: > Hi Everyone, > > When a variable is declared as const, it is initialized along with > the declaration, as modification later on is not possible. &...

problem about const member in a struct
Hi everyone, I have a problem. If I declare a struct with a const member, what will happen?For example: if I declared a struct like following: struct{ const int a; char c; }aStruct; then such statement as aStruct.a = 0; is illegal. But I can printf the value of a, it's always the same value no matter how many times I recompile the program. I'm wondering about how can the compiler ascertain the value of the const member? In an application, I wanna define a struct, whose first member is a const and its value is given by me, how can I do that? Neither K&R book nor "...

C
I have 3 different structures with each structure having the same first member (int type). I would like every structure of type 1 to have a 1 in the type field, every structure of type 2 to have 2 in the type field etc. I want instances of each structure to have the type value properly initialized, and I also want that member to be const. Basically, I want 1 member of a structure to be initialized to a value and be unchangeable. Is there a way to do this in C? Mas wrote: > I have 3 different structures with each structure having the same first > member (int type). I would like every ...

Can *common* struct-members of 2 different struct-types, that are the same for the first common members, be accessed via pointer cast to either struct-type?
Assume identical common top struct members: struct a { int i1; char c1; short sa1[3]; }; struct b { int i2; char c2; short sa2[3]; int differ_here; }; struct a tmp; Are the following 2 line always equivalent (as in: yielding the same lvalue) and allowed: tmp.c1 ((struct b*)&tmp)->c1 Thanks. - John. In article <37f36566-0b91-4ee4-9135-6890c7c8de7a@12g2000vba.googlegroups.com>, John Reye <jononanon@googlemail.com> wrote: > Are the following 2 line always equivalent (as in: yielding the same > lvalue) and allowed: Maybe not. The guarantee only ...

const and non-const iterators in const member functions
How can I make the method Company::find, below, const? The problem is that I have to declare 'i' to be a const iterator when 'find' is const. I cannot then safely convert it to non-const to return it. I do not understand precisely what is going on. It seems that in a const method the non-const version of 'begin' is not visible. struct employee { std::string name_; // int salary_; // etc ... }; bool name_is ( const employee &employee, const std::string &name ) { return employee.name_ == name; } class Company { ... private: typedef ...

const_cast in constructors to init const members
I have a base-class that have some protected members which will be initialised during construction, however since no derived classes (or members of the base-class) should change the values of those member I like to make the const. Unfortunately some of them are not trivial to initialise (i.e. they can not just be initialised from a value passed to the constructor. There are two ways I can construct these members, the first is by using helper-functions: class Bar { // Members const size_t m_nr; const std::vector<size_t> m_indices; // Helper function std::vector<...

Member variables declared as const references
I've got a question about member variables declared as constant references. Here is a simple class which holds a reference to a string and presumably does some non-mutating operations on it. class ScanString { public : explicit ScanString (const std::string& str) : str_ (str) { } private : const std::string& str_; }; The client is free to pass a string literal to the constructor: ScanString ("This is my immutable source string."); Now, I know that the standard states that in this case, a temporary string object is constructed, and by the rules of C++...

explicit calling of member template constructor...
Hi All, I have this example that attempts to call a member template constructor whilst explicitly specifying the template parameters. I realize that by using static_cast one can force the parameters to the right type (via argument deduction), but for normal member templates one [can] explicitly specify the template parameters. I would think there would be consistency here. Example: struct X { template <class T> X( T* p ); template <class T> X foo( T* p ); }; struct Base{}; struct Derived : Base{}; void foo( const X& ); int main() { ...