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 10633 articles. 8 followers. Post

2 Replies
1011 Views

Similar Articles

[PageSpeed] 27


  • 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...

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...

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...

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 ...

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() { ...

Declare a member variable of a class in the constructor
Is it possible to declare a class member variable in the constructor? For example, class SomeClass { public: SomeClass() { int SomeArray[10]; } } In this example, is it possible to make SomeArray[] a member variable without putting the declaration like this: class SomeClass { public: SomeClass(); private: int SomeArray[10]; } The reason I am asking this is that I would like to create an array whose size is determined by the parameters passed into the constructor. ankurd...@gmail.com wrote: > Is it possible to declare a class member varia...

Setting member variables before constructor call
Is the program at the end a correct C++ program? I ask because the output is: B::operator A&() A::A() B::B() B::~B() A::~A() that means the casting operator which sets the member variable B::p is called before the constructor of B. Here the program: #include <iostream> using std::cout; struct A { A(){ cout <<"A::A()\n"; } ~A(){ cout <<"A::~A()\n"; } }; struct B { B() // : p(0) // this kills the desruction of p { cout <<"B::B()\n"; } ~B() { cout <<"B::~B()\n"; delete p; ...

How to initialize a const char[] member variable
I'm using the gcc with the -pedantic setting. On my embedded system I need a parameter class that contains all setting for the software. This class needs to be ROM-able to locate it in some kind of eprom memory. Thus, all members of this class are const and there is only one static instance. An example header: class MyParameters { public: MyParameters() : m_nID(1), m_chDeviceName("The_Name") {}; const unsigned char m_nID; const char m_chDeviceName[9]; }; I get the error: ISO C++ forbids assignment of arrays .... in the header file. How can I solve thi...

Sorting lists by struct member variables
Hi, Bascically I want to sort a list by a member variable of a struct stored in the list. // ------------------------------ // Struct Header // ------------------------------ #include <string> struct Connection { int order; std::string url; int port; inline bool empty() { if ( (url.empty()) && (port == 0) ) { return true; } else { return false; } } }; // ------------------------------ // ------------------------------ // main // ------------------------------ std::list<Connection> lstconn; Connection conn; conn.order = 2 conn.url = www.eg2.com conn...

struct member with variably modified type
Section 6.7.2.1 p.8 forbids struct or union members with a variably modified type, but it is not a constraint. Before TC3, the constraint given in section 6.7.5.2 p.2 was (I am quoting N1124, should be pretty close to C99-TC2): "Only an ordinary identifier (as defined in 6.2.3) with both block scope or function prototype scope and no linkage shall have a variably modified type. If an identifier is declared to be an object with static storage duration, it shall not have a variable length array type." hence a struct member with a variably modified type was clearly a const.v...

Init const reference member in default constructor
Hi, I need a class "A" to be built only via my predefined constructor. Therefore I place the default constructor into the private section. The compiler obviously refuses any initalization of the const reference member from the default constructor I implemented. When I remove my default constructor, the compiler just eliminate the const reference member from the class A. Here is a sample code: class B{ public: B() {} virtual ~B() {} }; class A { public: A(const B& b): m_refB(b) {} virtual ~A() {} const B& m_refB; }; void main(){ B b; A a1(b); a1.m_refB; A a2(); a...

About member variable initilization and default constructor issues
In Inside C++ object Model, Lippman said there are four cases in which compile will sythesize a default constructor to initialize the member variables if the constructor is absent: 1. there is a virtual function; 2. virtual inheritance; 3.base class with explicit default constructor; 4.member object with explicit default constructor. e.g. class A { public: int i; A* p; } int main() { A a; if(a.i ==0 || a.p == 0) //do something } The behavior is undefined for the above case. If we modify class A to have any one of the four characeristics, then the member varia...

Const Multi-Dimentional Array Member Variable
I'd like to do something like this but having a problem with the proper syntax in the constructor, maybe someone knows the correct syntax? ---MyClass.h--- #ifndef MYCLASS_H_ #define MYCLASS_H_ class MyClass { public: MyClass(); virtual ~MyClass(); private: const char* const m_navi[1][1]; }; #endif /*MYMENU_H_*/ ---------- ---MyClass.cpp--- #include "MyClass.h" MyClass::Myclass() { m_navi = { {"1"} }; } MyClass:~MyClass() { } ---------- 1. I get an "expected ';' before '{' token" error at the "m_navi = {" line. I ...