473,785 Members | 2,714 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Iniitializing static const data?

How do we initialize static const data in C++, I tried
class Foo
{
static const std::string name = "MyName";
};
I don't see any reason as to why this must not work.

Probably it is because that we are in a sense calling a non static
function[ The constructor of std::string]. But any other soluction(?)
to me would sound inelegant.

But I see no rationale for not allowing

class Foo
{
static const float bar = 23;
};

Can anybody put any _common_sense in this non-sense.
--
Imanpreet Singh Arora
isingh AT acm DOT org
Jul 22 '05 #1
5 1714
Minti wrote:

How do we initialize static const data in C++, I tried

class Foo
{
static const std::string name = "MyName";
};

I don't see any reason as to why this must not work.

Probably it is because that we are in a sense calling a non static
function[ The constructor of std::string]. But any other soluction(?)
to me would sound inelegant.

But I see no rationale for not allowing

class Foo
{
static const float bar = 23;
};

Can anybody put any _common_sense in this non-sense.


What you are missing is that the above is a declaration, not a definition.
That is:
if you put a static member in a class, you only have declared it!
You still need a definition of that member somewhere and of course,
like anywhere else, you put the initialization to the definition.

Declaration: telling the compiler that somewhere, in a code snippet far far
away, something exists and what it looks like
Definition: reserves the actual memory for that something

So back to your example:

class Foo
{
static const std::string name; // Declaration
};

const std::string Foo::name = "MyName"; // Definition
Remember
There is the famous One-Definition-Rule. Which means:
you can have as many declarations in a program as you want (as long
as all of them coincide). But you can have only 1 defintion. Thus
typically the following is done. The declaration (enclosed in the class
declaration) goes into the header file, while the defintion (with the
initialization) goes into the source code file, which implements the
class functionality.

--
Karl Heinz Buchegger
kb******@gascad .at
Jul 22 '05 #2
Minti wrote:
How do we initialize static const data in C++, I tried
class Foo
{
static const std::string name = "MyName";
};
Initialisation of static constants is allowed in the class definition
_only_ for integral types. Members of any other types (and arrays,
pointers, references) has to be defined/initialised at the namespace
level.


I don't see any reason as to why this must not work.
The only reason relevant in comp.lang.c++ is that the Standard does
not allow that.
Probably it is because that we are in a sense calling a non static
function[ The constructor of std::string]. But any other soluction(?)
to me would sound inelegant.
I am not sure I understand the last sentence here.

But I see no rationale for not allowing

class Foo
{
static const float bar = 23;
};

Can anybody put any _common_sense in this non-sense.


Yes. Somebody definitely can, but you have to ask in comp.std.c++.
The questions about _why_ things are in C++ the way they are belong
there, not here. Here we can tell you _how_ to do things, but not
usually _why_ (unless it's explicitly explained in the C++ language
specification). Language lawyers and Standard Committee members are
often found in comp.std.c++ where all "why" questions are discussed.

Victor
Jul 22 '05 #3
Minti posted:
class Foo
{
static const std::string name = "MyName";
};

Consider you have a project like so:

monkey.cpp
ape.cpp
cow.cpp
tiger.cpp
fonte.cpp

fonte.hpp
Here's fonte.hpp:

#ifndef INCLUDE_FONTE_H PP
#define INCLUDE_FONTE_H PP

class Foo
{
static const std::string name;
};

#endif

Now consider that this header file is included into all of the above CPP
files. If you actually define the variable "name" in the header file, then
each translation unit would have it's own separate variable. You don't want
this, you just want the one variable. How you do this is make "fonte.cpp"
and put the following in it:

#include "fonte.hpp"

const std::string Foo::name = "BlahBlah";

See what happens now: the actual variable is declared in a .CPP file, that's
where the defintions go. If another CPP file, another translation unit,
wants to access this variable, all it does is include "fonte.hpp"
-JKop
Jul 22 '05 #4
JKop <NU**@NULL.NULL > wrote in message news:<gv******* **********@news .indigo.ie>...
Minti posted:
class Foo
{
static const std::string name = "MyName";
};

Consider you have a project like so:

monkey.cpp
ape.cpp
cow.cpp
tiger.cpp
fonte.cpp

fonte.hpp
Here's fonte.hpp:

#ifndef INCLUDE_FONTE_H PP
#define INCLUDE_FONTE_H PP

class Foo
{
static const std::string name;
};

#endif

Now consider that this header file is included into all of the above CPP
files. If you actually define the variable "name" in the header file, then
each translation unit would have it's own separate variable. You don't want
this, you just want the one variable. How you do this is make "fonte.cpp"
and put the following in it:

#include "fonte.hpp"

const std::string Foo::name = "BlahBlah";

See what happens now: the actual variable is declared in a .CPP file, that's
where the defintions go. If another CPP file, another translation unit,
wants to access this variable, all it does is include "fonte.hpp"

Hmm... Thanks for the answer but if we look at this whole thing with
an explanation that variables can only be declared in class
definitions then indeed we have a contradiction

class Foo
{
static const int foo = 23;
};

is allowed, the reason I believe is that it makes it easy to specify
the size of the arrays.

But this aan not be an explanation for making something incosistent.
--
Imanpreet Singh Arora "In order to paint 6 things are required:
i"kaur" #AT# acm #DOT# org spirit, rhythm, thought, scenery, pen
and ink"
mv kaur singh
Jul 22 '05 #5
Minti posted:

Hmm... Thanks for the answer but if we look at this whole thing with
an explanation that variables can only be declared in class
definitions then indeed we have a contradiction

class Foo
{
static const int foo = 23;
};

is allowed, the reason I believe is that it makes it easy to specify
the size of the arrays.

But this aan not be an explanation for making something incosistent.

My point is that no variable is created in your above code. Think of it as
an "extern" statement. It's just telling the compiler that such and object
exists, it's not saying that the variable is defined right here in this
translation unit!

The problem with your original code is that you were telling the compiler
that this object exists, but the when it came to the linker, the linker
couldn't find where the bloody thing was actually defined! That's why you
put:

const int Foo::foo = 23;

not 50 times, not 12 times, not twice, but once in one sole translation
unit. That way, when the linker sees loads of translation units saying that
this certain variable exists, it just goes through all of the translation
units looking for an actual definition, ie.:

const int Foo:foo = 23;

If it finds that more than once, then it's exactly the same as saying:
int main()
{
int a;

float a;

a = 23;
}
-JKop
Jul 22 '05 #6

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

Similar topics

29
4413
by: Alexander Mahr | last post by:
Dear Newsgroup, I'm somehow confused with the usage of the static keyword. I can see two function of the keyword static in conjunction with a data member of a class. 1. The data member reffers in all objects of this class to the same data Or in other word by using the static keyword all objects of one class can share data. (This is what I want)
3
3614
by: DanielBradley | last post by:
Hello all, I have recently been porting code from Linux to cygwin and came across a problem with static const class members (discussed below). I am seeking to determine whether I am programming non-standard C++ or if the problem lies elsewhere. To summarize static const class members are not being accessed properly when accessed from a DLL by another external object file (not within the DLL). It only occurs when the static const...
2
1765
by: trying_to_learn | last post by:
while seeing an example i was surprised to see that a const member function is allowed to change a static data member as shown below. I am trying to reason why.... and my guess is that static data members really dont belong to an object rather they belong to a class. however, isn't const a strict thing ? : where the compiler says "if u make this member function a const, i promise i wont let the function change the state of an object", yet...
3
1752
by: Thomas Matthews | last post by:
Hi, I've found with my compiler, that when a function contains const data in a function, that data is first copied to the stack. Given: /* Example 1 */ char Buffer; void My_Func(void)
2
6551
by: Robert Smith jr. | last post by:
Hello, Please pardon my newbie question ... I am building an ASP.NET page that displays a recordset with a Delete statement enabled (this all works fine). I want to Insert the current row *that is going to be deleted* into another table, before the original data is deleted. I am trying to use the RowDeleting method to call an Update or Insert
5
1868
by: Paul Smitton | last post by:
Hello, I would like to be able to store some constant data that is specific to each descendant class. This data would then be accessable by base class functions. However, I cannot find out how to do this. I thought the following would be a practical way of achieving this, but it will not work. Any help would be appreciated.
15
7872
by: akomiakov | last post by:
Is there a technical reason why one can't initialize a cost static non- integral data member in a class?
10
2207
by: oktayarslan | last post by:
Hi all; I have a problem when inserting an element to a vector. All I want is reading some data from a file and putting them into a vector. But the program is crashing after pushing a data which has string value. I really do not understand why push_back() function is trying to remove previously inserted data. Thanks for any help
5
2892
by: greek_bill | last post by:
Hi, I'm trying to develop a system where I can register some data/ information about a class. For example // ClassInfo.h template <class T> struct ClassInfo { static const std::string tagName;
0
9480
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
10319
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10147
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
10087
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
5380
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5511
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4046
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
3645
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2877
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.