0

Suppose we have this at a header file:

class A { private: static const double x; public: A(double given_x); }; class B { private: static const double x; class A; public: B(double x_given); }; 

And we need to initialize the static const data member of class A during initialization.
I thought that passing the variable x_given with initializer list from the constructor of B class to A class would be ok, but I'm apparently wrong.

How can this be done?

Also, both classes might need to have the same datamember.

Edit #1: I need to declare a const variable so as to ensure that it is not changed anywhere in the class member functions. But this value is given at construction time.

4
  • 2
    I can't figure out what you're asking. A static member isn't initialised in a constructor. Commented Feb 23, 2013 at 21:37
  • @sftrabbit: I've added clarification for what I want to do. Commented Feb 23, 2013 at 21:43
  • It makes no sense to initialize a static member in a constructor. It's static, it's already been initialized. Commented Feb 23, 2013 at 21:44
  • @EdS.: I've added clarification for what I need to do. So static might be wrong. I need it to be constant. Commented Feb 23, 2013 at 21:46

1 Answer 1

1

A static member has static storage duration, so it doesn't wait until an object is created before it is initialized. When you have a const static member of integral type, you can initialise it right there and then in the class definition. However, since yours is of type double, you need to define it in a single translation unit (such as in your A class's implementation file):

const double A::x = 48151623.42; 
Sign up to request clarification or add additional context in comments.

10 Comments

I cannot do this static const double x = 10.5; I am getting that only static const integral data members can be initialized within a class.
But still, I need to initialize a constant variable at the construction of the object, the value of which I don't know before construction. How can I implement this?
@Chris Does each instance of the object have its own value for x?
Nope, they'll all have the same, it's for the movement of some parts, so it will be the same. I've found out how to do it, I shouldn't have declared it as static. It's a const datamember not a static const one. Thank you for your help sftrabbit!
@Chris: Think about what you're saying for a moment. You want a constant value that is shared across all instances of your type. At the same time, you want each instance to initialize it. That makes no sense. You initialize it once at the class level, not N times at the instance level.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.