473,805 Members | 1,995 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Initialization inside a class


Hi,

Does anyone know why in C++, it is ok to initialize a const static int
inside a class, but you can't initialize a float?

From what I understand, initialization of const static float can only
be done inside a constructor.

For example:

class A
{
public:

const static int b = 123; // OK
const static double c = 123.456; // ERROR

A();
~A();
};
Roman
Jan 31 '06 #1
6 1807
* Roman:

Does anyone know why in C++, it is ok to initialize a const static int
inside a class, but you can't initialize a float?


Nobody _knows_ why, but the decision was made to support integral
constants so that they could be used in compile time expressions,
without generalizing the feature.

Generalization could be difficult.

For now, you can do one of two things if you want that value specified
in a header file:

* Place the constant outside the class, with internal linkage.
* Use the template constant trick.

Here's the template constant trick (perhaps I should apply for a
patent?):

template< typename T >
struct StrawberryConst ants { static const double pi; };

template< typename T >
double StrawberryConst ants<T>::pi = 3.14;

struct Dummy {};

class Strawberry: public StrawberryConst ants<Dummy>
{
// Whatever.
};

One may of course argue that the template constant trick means there's
no _technical_ reason why the language can't support that directly.
After all, any C++ compiler is required to be able to deal with it.
Perhaps it's just that these features were introduced in the "wrong"
order, and nobody's yet found it important enough to champion a clean-up
operation vis-a-vis the standardization committee.

--
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?
Jan 31 '06 #2
Roman wrote:

Hi,

Does anyone know why in C++, it is ok to initialize a const static int
inside a class, but you can't initialize a float?
Because the Standard says so.

From what I understand, initialization of const static float can only
be done inside a constructor. Incorrect. It needs to be done in the declaration of the static const
member.
For example:

class A
{
public:

const static int b = 123; // OK const static double c;
A();
~A();
};


const double A::c = 123.456;

See, that's not inside a constructor.
Jan 31 '06 #3

"Alf P. Steinbach" <al***@start.no > wrote in message
news:43******** ********@news.i ndividual.net.. .
* Roman:

Does anyone know why in C++, it is ok to initialize a const static int
inside a class, but you can't initialize a float?
Nobody _knows_ why, but the decision was made to support integral
constants so that they could be used in compile time expressions,
without generalizing the feature.

Generalization could be difficult.

For now, you can do one of two things if you want that value specified
in a header file:

* Place the constant outside the class, with internal linkage.
* Use the template constant trick.

Here's the template constant trick (perhaps I should apply for a
patent?):

template< typename T >
struct StrawberryConst ants { static const double pi; };

template< typename T >
double StrawberryConst ants<T>::pi = 3.14;

struct Dummy {};


I find little benifit of having to delcare Dummy{}; then to just have the
statement
StrawberryConst ants::pi = 3.14;

class Strawberry: public StrawberryConst ants<Dummy>
{
// Whatever.
};

One may of course argue that the template constant trick means there's
no _technical_ reason why the language can't support that directly.
After all, any C++ compiler is required to be able to deal with it.
Perhaps it's just that these features were introduced in the "wrong"
order, and nobody's yet found it important enough to champion a clean-up
operation vis-a-vis the standardization committee.

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

Jan 31 '06 #4

"Jim Langston" <ta*******@rock etmail.com> wrote in message
news:k5******** *******@fe03.lg a...

"Alf P. Steinbach" <al***@start.no > wrote in message
news:43******** ********@news.i ndividual.net.. .
* Roman:

Does anyone know why in C++, it is ok to initialize a const static int
inside a class, but you can't initialize a float?
Nobody _knows_ why, but the decision was made to support integral
constants so that they could be used in compile time expressions,
without generalizing the feature.

Generalization could be difficult.

For now, you can do one of two things if you want that value specified
in a header file:

* Place the constant outside the class, with internal linkage.
* Use the template constant trick.

Here's the template constant trick (perhaps I should apply for a
patent?):

template< typename T >
struct StrawberryConst ants { static const double pi; };

template< typename T >
double StrawberryConst ants<T>::pi = 3.14;

struct Dummy {};


I find little benifit of having to delcare Dummy{}; then to just have the
statement
StrawberryConst ants::pi = 3.14;


Of course I meant
const double StrawberryConst ants::pi = 3.14;

class Strawberry: public StrawberryConst ants<Dummy>
{
// Whatever.
};

One may of course argue that the template constant trick means there's
no _technical_ reason why the language can't support that directly.
After all, any C++ compiler is required to be able to deal with it.
Perhaps it's just that these features were introduced in the "wrong"
order, and nobody's yet found it important enough to champion a clean-up
operation vis-a-vis the standardization committee.

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


Jan 31 '06 #5
* Jim Langston:

I find little benifit of having to delcare Dummy{}; then to just have the
statement
StrawberryConst ants::pi = 3.14;


You don't have to.

Use "int" or whatever, although that will reduce readability by implying
the type matters (some libraries provide a ready-made Dummy type).

Btw. that should be "benefit" (your fault) and "const" (my fault).
Cheers,

- 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?
Jan 31 '06 #6
Roman wrote:
Hi,

Does anyone know why in C++, it is ok to initialize a const static int
inside a class, but you can't initialize a float?

From what I understand, initialization of const static float can only
be done inside a constructor.

For example:

class A
{
public:

const static int b = 123; // OK
const static double c = 123.456; // ERROR

A();
~A();
};


A simple workaround solution is to use an inline static function with a
static local variable.

class A
{
public:
const static int b = 123; // OK
static inline double get_c(){
const static double c = 123.456;
return c;
}
A();
~A();
};

Feb 1 '06 #7

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

Similar topics

6
3019
by: Alexander Stippler | last post by:
Hi, I wonder about the behaviour of como and icc on some very simple program. I thought initializing members of classes, which are of class type, would be 'direct initialized' (as the standard says). But in the example below the copy constructor of Vec is executed when initializing the Ref object. Is this standard conform? Doesn't it result in bad performance? #include <iostream>
1
4161
by: Jacek Dziedzic | last post by:
Hi! A) Why isn't it possible to set a member of the BASE class in an initialization list of a DERIVED class constructor (except for 'calling' the base constructor from there, of course)? I even tried prefixing them with BASE:: but to no avail. Still it's ok when I set them in the construtor body, not the init list. Does this mean that it's a small advantage of the initialization inside the constructor over initialization in the init...
1
3016
by: Piotr Sawuk | last post by:
just a quick question out of curiosity: how to initialize const arrays? struct srat { long num; ulong den; srat(){} } struct collisions
12
2338
by: Ricardo Pereira | last post by:
Hello all, I have a C# class (in this example, called A) that, in its constructor, starts a thread with a method of its own. That thread will be used to continuously check for one of its object's state and generate classe's A events "Connected" and "Disconnected". It looks something like this: "
5
1880
by: Randy | last post by:
Hi, When a class contains another class as a member variable, e.g., class ClassA { int a; public :
12
7182
by: Christoph Zwerschke | last post by:
Usually, you initialize class variables like that: class A: sum = 45 But what is the proper way to initialize class variables if they are the result of some computation or processing as in the following silly example (representative for more: class A:
16
2929
by: digitalorganics | last post by:
What's the difference between initializing class variables within the class definition directly versus initializing them within the class's __init__ method? Is there a reason, perhaps in certain situations, to choose one over the other? Thank you.
7
4033
by: Spoon | last post by:
Hello everyone, I have a Packet class I use to send packets over the Internet. All the packets sent in a session are supposed to share a common random ID. I figured I'd use a static const member inside my class. class Packet { static const int session_id;
1
3539
by: Sandro Bosio | last post by:
Hello everybody, my first message on this forum. I tried to solve my issue by reading other similar posts, but I didn't succeed. And forgive me if this mail is so long. I'm trying to achieve the following (with incomplete succes): I want in a given namespace Parameters a list of "initializers" (which are objects derived from a simple interface that can be implemented anywhere, and are used to define which parameters the program will take at...
0
9716
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10359
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
10364
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
10104
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
9182
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...
1
7645
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5677
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4317
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
3
3007
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.