473,788 Members | 2,810 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Simulatneous declare/initialize member variable

Are there any reasons that would make it bad for C++ to
allow simultaneous declaration and initilization of member data?

Current way:
------------

class DerivedClass : BaseClass {
{
enum { lengthSV=16 }; // Length of SomeVector
vector<double> SomeVector;

DerivedClass( void ) : BaseClass( SomeArgument ), SomeVector(leng thSV,0.0)
{
// Construction of Derived Class
};
};

Better/Worse way?
-----------------

class DerivedClass : BaseClass {
{
enum { lengthSV=16 }; // Length of SomeVector
vector<double> SomeVector(leng thSV);

DerivedClass( void ) : BaseClass( SomeArgument )
{
// Construction of Derived Class
};
};
Fred
--
Fred Ma
Dept. of Electronics, Carleton University
Ottawa, Ontario, Canada
Jul 22 '05 #1
10 3526
"Fred Ma" <fm*@doe.carlet on.ca> wrote...
Are there any reasons that would make it bad for C++ to
allow simultaneous declaration and initilization of member data?

Current way:
------------

class DerivedClass : BaseClass {
{
enum { lengthSV=16 }; // Length of SomeVector
vector<double> SomeVector;

DerivedClass( void ) : BaseClass( SomeArgument ), SomeVector(leng thSV,0.0) {
// Construction of Derived Class
};
};

Better/Worse way?
-----------------

class DerivedClass : BaseClass {
{
enum { lengthSV=16 }; // Length of SomeVector
vector<double> SomeVector(leng thSV);
This is not "better" or "worse". This is simply not allowed.

DerivedClass( void ) : BaseClass( SomeArgument )
{
// Construction of Derived Class
};
};


Victor
Jul 22 '05 #2
Victor Bazarov wrote:


This is not "better" or "worse". This is simply not allowed.

Yes, I know it's not allowed. Wouldn't the code be clearer and
more compact if it was allowed? Perhpas there are some reasons
that it isn't allowed.

Fred
--
Fred Ma
Dept. of Electronics, Carleton University
Ottawa, Ontario, Canada
Jul 22 '05 #3

"Fred Ma" <fm*@doe.carlet on.ca> wrote in message
news:40******** *******@doe.car leton.ca...
Are there any reasons that would make it bad for C++ to
allow simultaneous declaration and initilization of member data?


Your question is not specific to vectors, it holds for all data members.
For example you can have an "int i;" declaration as a class member, so your
question would also be: what problem could exist with using "int i(-3);"
instead of having to set the value in a constructor?

I think one answer may be that different constructors will initialize data
members differently, so a single declaration (of the type you refer to)
would need to be over-ridden by a constructor that needs something
different. Constructors that are fine with the default value would just
leave it alone. But this would make the code less coherent as readers would
have to refer to more than just the constructor to determine what values are
given to all members. Instead of having everything in a single location,
now you need to look at both the constructor and the data declaration to
find out what values are given to all members.

Maybe the question boils down to what is truly needed against what may be
nice to have but is not essential.
Jul 22 '05 #4
qWake wrote:

"Fred Ma" <fm*@doe.carlet on.ca> wrote in message
news:40******** *******@doe.car leton.ca...
Are there any reasons that would make it bad for C++ to
allow simultaneous declaration and initilization of member data?


Your question is not specific to vectors, it holds for all data members.
For example you can have an "int i;" declaration as a class member, so your
question would also be: what problem could exist with using "int i(-3);"
instead of having to set the value in a constructor?

I think one answer may be that different constructors will initialize data
members differently, so a single declaration (of the type you refer to)
would need to be over-ridden by a constructor that needs something
different. Constructors that are fine with the default value would just
leave it alone. But this would make the code less coherent as readers would
have to refer to more than just the constructor to determine what values are
given to all members. Instead of having everything in a single location,
now you need to look at both the constructor and the data declaration to
find out what values are given to all members.

Maybe the question boils down to what is truly needed against what may be
nice to have but is not essential.


Definitely, it's not essential (few things are). I was just wondering why
it is necessary to move such a simple initialization to the derived class's
constructor (specifically, to form an initialization list). A person then
has to look at the declaration to see the data member, the the appropriate constructor to see the initialization. Right now, the initialization lists
that follow the different constructors override the default value of member
anyway. That is, if the member variable is not specified in an initializer
list, it is left alone. Otherwise, the initialization list takes precedence.
At the moment, I can't recall if the member variables becomes zero if it
doesn't show up in the initialization list, but that is immaterial. It is
left alone regardless. So it is no less confusing to allow the user to
specify the default initialization for a data member in the case that it
doesn't show up in an initialization list. In the current case, where it
isn't allowed, you must still keep in mind either the zero default or the
simply unknown value default.

The reason this comes to mind is because C++ has enough bells and whistles
and a myriad of nuances to keep in mind already. Different details specified
at various places. The more streamline the code, the better. The above
change wouldn't detract from any functionality. If it doesn't collide with
any other syntatic requirements, it would certainly help in managing all
the features and details.

Fred
--
Fred Ma
Dept. of Electronics, Carleton University
Ottawa, Ontario, Canada
Jul 22 '05 #5
Fred Ma wrote:
Victor Bazarov wrote:

This is not "better" or "worse". This is simply not allowed.


Yes, I know it's not allowed. Wouldn't the code be clearer and
more compact if it was allowed? Perhpas there are some reasons
that it isn't allowed.


Perhaps. I am not going to speculate about it. Please ask in
comp.std.c++, they discuss the "why it's so in the Standard".

V
Jul 22 '05 #6
"Fred Ma" <fm*@doe.carlet on.ca> wrote in message
news:40******** *******@doe.car leton.ca...
That is, if the member variable is not specified in an initializer
list, it is left alone.


I think instances that are not explicitly initialized hold garbage unless
they have a default constructor. Your idea has the merit that simple types
could behave within a class as if they also had a default constructor.
Perhaps you should ask the question in comp.std.c++ for a more informed
reply.
Jul 22 '05 #7
Fred Ma <fm*@doe.carlet on.ca> wrote in message news:<40******* ********@doe.ca rleton.ca>...
Are there any reasons that would make it bad for C++ to
allow simultaneous declaration and initilization of member data?


Yes, more or less. Difference ctors might need to initialize a
variable differently. As-is, the rule is consistent: non-static
members are initialized on the ctor. I doubt that the rules could be
kept nearly this consistent otherwise. Just for example, if you had
something like:

class X {
int x=0;
public:
X() : x(1) {}
};

how would you deal with it? Consider it ill-formed (keeping in mind
that the class definition will often be visible in places that the
ctor isn't)? Start with 0 and then assign 1? Start with 1 and then
assign 0? What would you do if (for example) instead of an int, this
was an instance of some other class that only supported initialization
and NOT assignment?

Ultimately, I suspect each of these questions _could_ be answered, but
doing so would probably lead to quite a few more. In the end, all the
questions might have answers, but I doubt anybody has gone to the
trouble of figuring out for sure -- most of the people on the
committee are pretty busy to start with, so in general, committee work
gets prioritized, and something that adds a lot of questions but
little or no new utility is likely to get quite a low priority.
--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 22 '05 #8
Jerry Coffin wrote:

Difference ctors might need to initialize a
variable differently. As-is, the rule is consistent: non-static
members are initialized on the ctor. I doubt that the rules could be
kept nearly this consistent otherwise. Just for example, if you had
something like:

class X {
int x=0;
public:
X() : x(1) {}
};

how would you deal with it? Consider it ill-formed (keeping in mind
that the class definition will often be visible in places that the
ctor isn't)? Start with 0 and then assign 1? Start with 1 and then
assign 0? What would you do if (for example) instead of an int, this
was an instance of some other class that only supported initialization
and NOT assignment?

Ultimately, I suspect each of these questions _could_ be answered, but
doing so would probably lead to quite a few more. In the end, all the
questions might have answers, but I doubt anybody has gone to the
trouble of figuring out for sure -- most of the people on the
committee are pretty busy to start with, so in general, committee work
gets prioritized, and something that adds a lot of questions but
little or no new utility is likely to get quite a low priority.


Admittedly, this could be naive, but it seems to me to be
straightforward to avoid ambiguity without much to consider. The
compiler will flag an error if initialization is specified at both the
declaration and an initialization list. Hence, programmers can use
simultaneous declaration/initialization only for parameters for which
it makes sense (i.e. for variables which the author intended to be
unchangable). It seems preferable to having a static member, since
the value is right at the same location as the declaration.

If the data member wasn't an int, and didn't have an assignment
operator, just initialize it in the way that you would any object at
declaration:

class X
{
int x(0);
// ...
};

This is not to suggest that this idea will be welcome or noticed by
any significant number of people (or any at all), especially
overworked standards committe people. Just to say that there don't
seem to be any real difficulties with it.

Some might think it less clear to have the initialization value
separate from the constructor, but there are some parameters
for which it just makes sense for value to be readily apparent
when the variables declaration is seen. Mostly constants, or
near-constants. If the class definition is seen as a "table of
contents", or "map", of the class structure, it makes sense to have
those values right up front. Easier to look up compared to tucking it
away in constructors somewhere. And it simplifies the constructor's
initialization list.

Fred
Jul 22 '05 #9
<snip>
Some might think it less clear to have the initialization value
separate from the constructor, but there are some parameters
for which it just makes sense for value to be readily apparent
when the variables declaration is seen. Mostly constants, or
near-constants. If the class definition is seen as a "table of
contents", or "map", of the class structure, it makes sense to have
those values right up front. Easier to look up compared to tucking it
away in constructors somewhere. And it simplifies the constructor's
initialization list.

Fred


From the description of your needs it looks like what you're talking about is
something that is already allowed. Per-class constants. If you have a
static const member variable of an integral type you can initialize it
right in the class definition.

class A
{
static const int nClassID = 100;
};

Of course, you could always use enums.

Andy.
Jul 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
677
by: David T. Ashley | last post by:
Hi, In my project, I typically declare and define variables in the .H file, i.e. DECMOD_MAIN UINT8 can_message_201_status_global #ifdef MODULE_MAIN = HAS_NEVER_BEEN_RECEIVED #endif ;
5
4575
by: Jim Langston | last post by:
What I want to do: have a vector of ints in my class initialized with 0 to 499 which will later be pushed/popped out of the vector by instances. What I have: class CParticleStream // Yes, I know you wouldn't use 'C' { private: static std::vector<int> PSArray; public:
30
6816
by: Javaman59 | last post by:
I come from a background of Ada and C++ programming, where it was considered good practice to explicitly initialize every variable. Now that I'm programming in C# I think that it would be best NOT to initialize class members, because every type has well defined initialization anyway. eg. class C
15
5326
by: Geoff Cox | last post by:
Hello, Can I separately declare and initialize a string array? How and where would I do it in the code below? It was created using Visual C++ 2005 Express Beta 2 ... In C# I would have private string myArray;
3
20878
by: johnmmcparland | last post by:
Hi all, I would like to have a static constant array inside a class definition which would contain the number of days in each month (I am writing a Date class as an exercise). However my attempts so far have been unsuccessful. Take this Test class as an example // test.hpp
4
8369
by: Bram Kuijper | last post by:
Hi all, as a C++ newbie, I got some question on the initialization of static reference data members. Since it isn't possible to initialize static members of a class in the constructor, I should initialize them in advance. However, the following code, in which I first produce two classses and then try to assign a reference of the first class to a static data member of the second class doesn't work. It gives the following compiler error:
1
2786
by: ares.lagae | last post by:
- I have a typelist and I want to declare a member variable for each of the types. How can I do that? E.g. I have the typelist "typedef boost::mpl::vector<int, float> types;" and I want to declare member variables with type "int" and "float". - I have a typelist and I want to declare a variable based on each of the types types. How can I do that? E.g. I have the typelist "typedef boost::mpl::vector<int, float> types;" and I want to...
11
8335
by: Jef Driesen | last post by:
I have the following problem in a C project (but that also needs to compile with a C++ compiler). I'm using a virtual function table, that looks like this in the header file: typedef struct device_t { const device_backend_t *backend; ... } device_t; typedef struct device_backend_t {
2
5192
by: rpm27 | last post by:
Hey everyone, I am trying to declare a static class variable (not a 'primitive' variable, but from a class i wrote) inside a class However, I have tried several ways to initialize it and they all caused compilation errors: #include "MyClass.cpp" class A
0
9498
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9967
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6750
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5536
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4069
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.