or.nomore
or.nomore

Reputation: 925

How to create a initialization function that only read once in c++

I have this class:

class A : public B

and i need to add some protected field: _field, in A and I can't touch/change B. Now, all the function in B and A are virtual except the constructor. Obviously, _field is not part of class B.

I need to initialize _field. How can i do that if the only constructor is B's? Also, something like this:

unsigned long _field = 0;

gives me an error compilation.

I solve this by:

class A : public B
{
protected: 
  unsigned long _field;
public:
  void fooFunction(){
     ....do other stuff....
     static bool isInitField = false;
     if (!isInitField){
       _field = 0;
       isInitField = true;
     }
     ...rest of the function...
  }

Is there a better way to do that without using static?

Thanks, Or

Upvotes: 0

Views: 79

Answers (2)

HBY4PI
HBY4PI

Reputation: 89

Pardon me, actually I haven't understood your problem. As far as one time initialization is concerned, constructor is the place to do it. But your proposed solution hints that you want something else.

static in function definition would make _field only one time modifiable across all objects of the class and this is a bit awkward mechanism to make _field one time modifiable.

If you want to just initialize _field then use initialization. Solution by Esteban would do. Better use

A(unsigned long i, other_paramaters oth) : B(oth),_field(i) { }

and

A(params):B(params),_field(0){}

Upvotes: 1

Étienne
Étienne

Reputation: 4994

Use A constructor and call B constructor in the initialization list, this way you initialize all fields of class A:

A(unsigned long i, other_paramaters oth) : B(oth),_field(i) {

}

Upvotes: 2

Related Questions