user1873947
user1873947

Reputation: 1821

Changing initialization order in constructor

 class a
 {
 public:
 a() : b(5), a1(10) //will firstly initialize a1 then b, so order here doesn't matter
 int a1;
 private:
 int b;
 }

The question is how to change the order (to have b initialized before a1)? I must have public members above private so that solution isn't okay for me. Of course here I use ints, the problem is more complex but it's just an example which shows what is my problem.

Upvotes: 1

Views: 1330

Answers (4)

AndersK
AndersK

Reputation: 36092

If I understand you correct you have some kind of style guide saying that public members should be before private.

In that case I would suggest you declare all your member variables private and create accessor functions to them instead. That way you get around it.

class a
 {
 public:
   a() : _a1(5), _b(10) 
   int a1() const { return _a1; }
   void a1(int value) { _a1 = value; }
   int b() const { return _b; }
   void b(int value) { _b = value; }

 private:
   int _a1;
   int _b;
 }

any sane compiler will anyway optimize it so the overhead will be minimal.

Upvotes: 2

Mats Petersson
Mats Petersson

Reputation: 129524

Make your b object private, declared it before a1, and make an accessor function for accessing the content of b. [If necessary, make it return a reference to the b object, so the calling code can modify it - although that is quite clearly bad design to expose the internals of a class to the calling code, whether it's through a public declaration or through returning a reference]

Upvotes: 1

Andy Prowl
Andy Prowl

Reputation: 126582

You cannot change the order of initialization, that is always defined by the order of declaration of the members in your class. This is necessary because the order of destruction must be the inverse of the order of construction, and if you changed the order of construction, the compiler would be forced to keep track of which order you have initialized your members in in order to generate proper destruction sequences.

So my advice is:

  1. Just live with it, and;
  2. Do not depend on the order of construction of your member variables.

To achieve point 2), you can provide default constructors for your members to do default initialization, and then initialize your members properly in the order you want inside the body of your constructor (in other words, decouple construction from logical initialization).

Upvotes: 5

juanchopanza
juanchopanza

Reputation: 227618

The order of initialization is determined by the order of declaration of the member variables. So if you want b to be initialized before a, you have to declare it before.

class a
{
  public:
   a() : b(5), a1(10) {}
  private:
   int b;
  public:
   int a1;
};

Upvotes: 3

Related Questions