f



Initialization of data members inside a class

Is it permissible to initialize non-static data members inside a class,
like so?

class whatever
{
   int x = 9;
   const int y = 10;
....
};

If so, is there a reference in the "standard" that grants this
permission, and when did this syntax come about?

Thanks


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

0
Joe
2/21/2016 1:20:11 PM
comp.lang.c++.moderated 10738 articles. 1 followers. allnor (8509) is leader. Post Follow

3 Replies
497 Views

Similar Articles

[PageSpeed] 18

Joe Bentley <joe.foxhound@googlemail.com> writes in comp.lang.c++.moderated:
>Is it permissible to initialize non-static data members inside a class,
>like so?
>class whatever
>{
>   int x = 9;
>   const int y = 10;
>...
>};
>If so, is there a reference in the "standard" that grants this
>permission, and when did this syntax come about?

  When an object of the above class is being default-initialized,
  its constructor is called with an empty argument list (9.5p7).

  Then, according to 12.6.2p9, �In a non-delegating
  constructor� (9.1), �if the entity is a non-static data
  member that has a brace-or-equal-initializer� ... 
  �the entity is initialized as specified in 8.5;�.

  8.5p17.8 then says, �the initial value of the object being
  initialized is the (possibly converted) value of the
  initializer expression.�

0
ram
2/22/2016 2:42:10 AM
Assuming that
   http://en.cppreference.com/w/cpp/language/class#Member_specification
is consistent with the standard, I'd say yes.

Norbert

Joe Bentley wrote:
>
> Is it permissible to initialize non-static data members inside a class,
> like so?
>
> class whatever
> {
>     int x = 9;
>     const int y = 10;
> ...
> };
>
> If so, is there a reference in the "standard" that grants this
> permission, and when did this syntax come about?
>
> Thanks


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

0
Norbert_Paul
2/22/2016 6:47:37 AM
[Please do not mail me a copy of your followup]

Joe Bentley <joe.foxhound@googlemail.com> spake the secret code
<a8d71d07-329c-41de-a5ff-ff5a06e3017d@googlegroups.com> thusly:

>Is it permissible to initialize non-static data members inside a class,
>like so?
>
>class whatever
>{
>   int x = 9;
>   const int y = 10;
>...
>};

Yes

>If so, is there a reference in the "standard" that grants this
>permission, and when did this syntax come about?

This was introduced in C++11.

See <http://en.cppreference.com/w/cpp/language/data_members> for C++11
and C++14 specific discussion on member initialization.
-- 
"The Direct3D Graphics Pipeline" free book <http://tinyurl.com/d3d-pipeline>
     The Computer Graphics Museum <http://computergraphicsmuseum.org>
         The Terminals Wiki <http://terminals.classiccmp.org>
  Legalize Adulthood! (my blog) <http://legalizeadulthood.wordpress.com>


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

0
legalize
2/22/2016 2:26:17 PM
Reply:

Similar Artilces:

error Message: "only const static integral data members can be initialized inside a class or struct"
Hi, I got this error msg whilst building some classes. It is realatively asy to fix. But I just wondered, does anyone know the technical reason why one can't initialiaze a const static non-integral data member in a class? "Susan Baker" <sbaker@no.spam.net> wrote in message news:da8j1a$alj$1@nwrdmz02.dmz.ncs.ea.ibs-infra.bt.com > Hi, > > I got this error msg whilst building some classes. It is realatively > asy to fix. But I just wondered, does anyone know the technical > reason why one can't initialiaze a const static non-integral data > member i...

Class Member Data and Member Function Parameters
Hello: First, if this is one of those "questions asked a million times" just say so and I'll dig a little deeper. If not, then... I'm curious, is it typical to use member data (properties, attributes, etc.) as parameters to the class's member functions or would you normally have parameters that are not data members of the class? Or is it normally a combination, just depending on circumstances? Did I make sense? If anyone knows of any books that talk about this, I'd appreciate a title, etc. I guess I'm asking which is the better design. Example: Is it bett...

Possible for C++ class to force derived class to contain static data member?
Hello, I fear I want to have something which is not possible in C++. How is it possible to define a base class so that the derived class is forced to contain a static member variable, which can be used by static member functions of the base class? Something like virtual static XClass* pXClass; /* pXClass shall be pure virtual, so not static in base class, but static in derived class */ The static class related part of the derivation could so provide manager functionality for the object instances of the class. The only solution I currently see is to have a base class containing XClass* pXCla...

C++ in-class member initialization
Before I fell asleep last night, I had the following idea for in-class member initialization with no runtime overhead. What do you think? #define INCLASS_INIT(ctype, name, ...) \ class _ ## name ## _INIT { \ private: ctype m_data; \ public: \ inline _ ## name ## _INIT() : \ m_data(__VA_ARGS__) {} \ inline _ ## name ## _INIT(const ctype& v) : \ m_data(v) {} \ inline operator ctype&() \ { return m_data; } \ inline operator const ctype&() const \ { return m_data; } \ inline ctype* operator&() \ { retu...

Class data members in C
Hmm. The extensions documentation describes how to add instance members to a class (PyMemberDef), but I want to add a class member. Yes, this is constant for all instances of the class. Any pointers? Regards, Nick Maclaren. Nick Maclaren wrote: > Hmm. The extensions documentation describes how to add instance > members to a class (PyMemberDef), but I want to add a class member. > Yes, this is constant for all instances of the class. > > Any pointers? Add something like this to your PyMODINIT_FUNC after you have initialized your type with PyType_Ready: PyDictSetItemStrin...

Initializing data members in C++0x
My understanding is that C++0x allows non-static data members of any type to be given a default initialization value, e.g., class Widget { double fudgeFactor = 1.5; // default init. value for non-static double }; My reading of 9.4.2 in N2800 is that the corresponding syntax for static data members is invalid, because such initialization is allowed only for const statics initialized with integral constant expressions. So this appears to be okay, class Widget { static const double d = 1; // initializer is integral }; but this does not: class Widge...

C++ .NET class member initialization
Hi, I'm wondering how C++ .NET initializes class members. I have code that looks aproximately like this: _gc class SuperClass; // Factory object creates instances _gc class Factory { public: virtual SuperClass* createInstance() = 0; }; // Common interface _gc class SuperClass { public: // available class factories static ArrayList *factories = new ArrayList(); static SuperClass* createInstance(int factory) { return dynamic_cast<Factory*> (factories[factory])->createInstance() } virtual void doSomething(void) = 0; }; // Class implementating SuperClass interface _...

where/when should I initialize static class data members?
They should be initialized before any instance is created. I have no idea in which file, in which place should I put their initialization code to be sure they are initialize only once, before any instance is created. I cannot visualize the control flow of an executing program when the code is split in multiple files. r.z. <gklkj@hjkjhk.pl> wrote: > They should be initialized before any instance is created. I have no idea in > which file, in which place should I put their initialization code to be sure > they are initialize only once, before any instance is created. >...

Class members that MUST be initialized by temporary objects in a member initialization list
Hello C++ gurus, I've got this basic class thats the backbone of my project and I frequently use use an instance of it to initialize other objects like so. However, my latest class, a simple assignment in a constructor did not work, like so: class VeryBasicClass{ public: VeryBasicClass(){}; }; class LatestClass{ public: LatestClass( VeryBasicClass &vbo ); private: VeryBasicClass veryBasicObject; }; LatestClass::LatestClass( VeryBasicClass &vbo ) { veryBasicObject = vbo; // this does not work // halts plugin execution } The following constructor caused the environment...

initialization of static data members in template class
I'm trying to use a template class containing a static data member, but I'm having trouble with the definition/initializations of these static data members. In particular, consider the following test code (heavily abstracted from my actual production code): #include <cstdio> class real_scalar_field { }; class complex_scalar_field { }; class second_order_FD { }; class fourth_order_FD { }; template <class physics_system, class FD_scheme> class chunk { }; // explicit instantiations template class chunk< real_s...

Are members of a c++ class initialized to 0 by the default constructor ?
Hello, My question is basically: Are members of a c++ class initialized to 0 by the default constructor ? For example: class TSomeClass { private: int mField1; int mField2; protected: public: TSomeClass(); ~TSomeClass(); }; // constructor TSomeClass::TSomeClass() { } // destructor TSomeClass::~TSomeClass() { } Usage example: class TSomeOtherClass { private: TSomeClass mSomeClass(); public: // default constructor here etc. } int main() { TSomeClass vSomeClass(); TSomeClass *vSomeClassArray; vSomeCl...

Integral const static member initialized inside a class
In the book C++ Primer(Fourth Edition) by Stanley Lippman, the following is mentioned in page 471(Under the subsection "Intergral const static Members Are Special") "When a const static data member is initialized in the class body, the data member must still be defined outside the class definition." Here I understand that the data member should be of integral type. But I do not get compilation error even if I do not define the integral const static data member outside the class. Consider the following program named x.cpp: #include <cstdlib> #include <...

initialization of a const static float data member in a class
Is there a technical reason why one can't initialize a cost static non- integral data member in a class? * akomiakov@gmail.com: > Is there a technical reason why one can't initialize a cost static non- > integral data member in a class? No, it's mostly political (would drag in lots of other considerations). Cheers, & hth., - Alf -- A: Because it messes up the order in which people normally read text. Q: Why is it such a bad thing? A: Top-posting. Q: What is the most annoying thing on usenet and in e-mail? akomiakov@gmail.com wrote: > Is there a technical reason...

Class member initializers in class declaration
===================================== MODERATOR'S COMMENT: Apologies for the delay in moderation; this appears to be caused by my ISP (Cox) dropping and/or blocking e-mail. ===================================== END OF MODERATOR'S COMMENT A common bug I often see is uninitialized member variables. I believe the main reason for this is being unable to initialize class members where they are declared. Because class members are initialized separately from their definition, it can often be difficult to spot which variables are being initialized and which ones are not. I&#...

Class as data member of another class
Given these two (incomplete but representative) classes in two seperate header files: Class1.h class Class1 { public: Class(const char CharValue, const int IntValue1, const int IntValue2); ~City(); private: }; Class2.h #include "Class1.h" class Class2 { public: Class2(const int IntValue1, string StringValue); ~Class2(); private: Class1 Class; }; and an implementation file for Class2: Class2.cpp Class2::Class2(const int IntValue1, string StringValue) { Class('A', 30, 30); // trying to create an object of type Class1 within the constructor of Class2 } ...

Help in understanding initialization of data members of class (esp. static)
Hello. I have been trying to understand how the initialization of data memb= ers of a class happens, esp. static members. I should note that I am using = GCC 4.6.3 (64 bit) that came with Kubuntu Precise for my testing, so the er= ror messages I inline in comments are from that. And all of the errors are = compiler errors except for one which I have marked as a linker error.=20 I have inlined my queries in comments with three slashes: /// -- I would mu= ch appreciate clarifications to those queries. Thank you very much in advan= ce! struct a { a () {} // int i =3D 1 ; // stat...

static const non-integral data members initialized within a class
In MSVC8.0, static const integral data members can be initialized within a class, but not the non-integreal data members, such as double. In GCC, it is not the case. Code like below: struct MM { const static double mm = 0.0; }; This can be compiled error in MSVC8.0 with the message: " error C2864: 'MM::mm' : only static const integral data members can be initialized within a class "; but it is right in GCC. So I want to know, according to the standard, which is right , MSVC8.0 or GCC? Thanks! -- [ See http://www.gotw.ca/resources/clcm.htm for info about ] ...

can't initialize static data member in triply-nested class
I'm getting a surprising compiler error when I try to initialize a static data variable in a triply-nested class. I'm using Visual C++ 6. Am I doing something wrong here (other than by using Visual C++ 6)? class A { private: class B { private: class C { private: }; static C *p2; }; static B *p1; }; A::B *A::p1; // ok A::B::C *A::B::p2; // error! The error is "cannot access private class declared in class 'A::B'". I don't see why p1 should be ok, but p2 no...

C code in C++ and used inside class
Im trying to use some C code inside a C++ class, this class is used in another C++ class ofcourse, or will be. The C++ class will contain a data structure from the C code amongst others. But in the C code header file where the datatype is defined, there are also some global variables defined. Is there a way to avoid multiple inclusion error, without changing the C code? Michael On 4 Ago, 19:21, "cognacc@" <michael.cogn...@gmail.com> wrote: > Im trying to use some C code inside a C++ class, this class is used > in another C++ class ofcourse, or will be. > The C++ ...

class data member or member function argument?
When designing a class, how do you know whether to make a variable a private data member or just an argument to the class's member functions? If I make it a private data member, then it's imperative I have a valuie for it at the time I create the object (put it in the constructor). On the other hand, if I just use it as a member function argument, then I have to be responsible for defining and initializing the variable before the object is created, and then deleting the variable after the object is deleted. THis leads to code like this: // code begins here // ... define and initialize...

9.2/2 Suggestion: the class should be complete within nested enumerator definitions and static data member initializers
Consider the following code snippet: struct C2027 { static char buf[01]; static unsigned const buf_size_1 = sizeof buf; static unsigned const buf_size_C2027 = sizeof static_cast<C2027 const *>(0)->buf; // error C2027: use of undefined type 'C2027' void fun(unsigned = sizeof static_cast<C2027 const *>(0)->buf); // OK }; According to the standard, this snippet is malformed: "ComeauTest.c", line 4: error: pointer to incomplete class type is not allowed static unsigned const buf_size_C2027 = sizeof static_cast<C2027 const *>(0...

Proposal: Initialization of Class Members within Class Definition
I would like to see something like: class XYZZY { ... SOMETYPE *ptr = 0 ; } ; within the class definition to serve as the default initialization of a member. Such an initialization could be overriden in the constructor. XYZZY::XYZZY (...) : ptr (&q) { } Reasoning: 1. This would help eliminate/reduce duplicate initializations in classes with multiple constructors. 2. Improve reliability by providing a convenient mechanism ensure data members are initialized and providing a means to verify the initialization. --- [ comp.std.c++ is moderated. To subm...

How to transfer data structure or class from Python to C/C++?
Hi friends, I am a newer of Python. I want to ask below question: I have a C/C++ application and I want to use Python as its extension. To do that, I have to transfer some data structure from C/C++ application to Python and get some data structure from Python to C/C++ application. I have researched Python document, but the example only describes how to transfer some simple data, such as integer,char, etc. Could you please guide me to do that? or tell me some document to have a research? Thanks. Hongtian: > Could you please guide me to do that? or tell me some document to have > a re...

size of class same as base class if no new data members?
Can I assume that if I have: class A { /* a few built in types */ }; class B : public A { private: //prevent copy and assignment B( B const & ); operator=( B const & ); }; instances of class A will be the same size as instances of class B? More particularly, if I have: std::vector< A > v(2); B *b = static_cast< B * >( &v[0] ); ++b; will b point to the second element of v? Does the standard offer any guarantees? My motivation is that I want to be able to grow a vector of As, but prevent clients from copying them thereafter. I realize that I am ...

Web resources about - Initialization of data members inside a class - comp.lang.c++.moderated

Initialization vector - Wikipedia, the free encyclopedia
is a fixed-size input to a cryptographic primitive that is typically required to be random or pseudorandom . Randomization is crucial for encryption ...

Booting an Intel Architecture System, Part II: Advanced Initialization
Once the processor is running and memory has been initialized, timers and devices must be started up and a memory map laid out. Only then, can ...

Patent US6061520 - Method and system for performing static initialization - Google Patents
... consolidating class files, the preloader identifies all &lt;clinit&gt; methods and play executes these methods to determine the static initialization ...

Initialization practices disqualify UN IPCC global circulation models from use for most climate change ...
Guest essay by Michael G. Wallace Hydroclimatologist, Albuquerque, NM The United Nations Intergovernmental Panel on Climate Change UN IPCC features ...

Spring Environment is for initialization code only - Java Code Geeks
Since version 3.1, the Spring framework offers an abstraction towards several different sources through which you can easily configure your application: ...

Ball Invasion for iPad2 for iPad on the iTunes App Store
Get Ball Invasion for iPad2 on the App Store. See screenshots and ratings, and read customer reviews.

Stack Overflow
Stack Exchange log in - careers - chat - meta - about - faq Questions Tags Users Badges Unanswered Ask Question Top Questions interesting 325 ...

Copland (operating system) - Wikipedia, the free encyclopedia
Copland was a project at Apple Computer to create an updated version of the Macintosh operating system . It was to have introduced protected ...

ESANN - Author index
Electronic preceedings author index ESANN - European Symposium on Artificial Neural Networks [ Electronic proceedings home page ] A B C D E F ...

Using event capturing to improve Basecamp page load times
... would be best if we could avoid initializing sortables until the last possible moment, just before you start to drag a to-do. Deferring Initialization ...

Resources last updated: 2/22/2016 4:03:25 PM