Simplicity
Simplicity

Reputation: 48916

What is this struct trying to do?

In the following C++ code:

struct Features {
  int F1;
  int F2;
  int F3;
  int F4;
  Features(int F1,int F2,int F3,int F4)
  : F1(F1), F2(F2), F3(F3), F4(F4) { }
};

What does this part mean?

Features(int F1,int F2,int F3,int F4)
      : F1(F1), F2(F2), F3(F3), F4(F4) { }

Thanks.

Upvotes: 2

Views: 143

Answers (3)

juanchopanza
juanchopanza

Reputation: 227390

It is initializing the member variables using the constructor's initializer list. it would be clearer if the names of the constructor parameters weren't the same as the data members:

Features(int a,int b,int c,int d)
      : F1(a), F2(b), F3(c), F4(d) { }

It is useful to have some naming convention for data members, such that these are easily identifiable and distinguishable from local variables in code. Examples are prefixing an m_ or using a trailing _:

struct Features {
  int m_f1;
  int m_f2;
  int m_3f;
  int m_f4;
  Features(int f1,int f2,int f3,int f4)
  : m_f1(f1), m_f2(f2), m_f3(f3), m_f4(f4) { }
};

Both these constructors can be used like this:

Features f(11,22,33,44);
std::cout << f.m_f1 << "\n"; // prints 11
std::cout << f.m_f2 << "\n"; // prints 22
std::cout << f.m_f3 << "\n"; // prints 33
std::cout << f.m_f4 << "\n"; // prints 44

Note that the fact that this constructor has been defined means that the compiler will no longer provide a default constructor. So if you want to be able to to this:

Features f;

then you need to provide your own default constructor:

Features() : m_f1(), m_f2(), m_f3(), m_f4() {} // initializes data members to 0

Upvotes: 8

Andrew
Andrew

Reputation: 24846

It is member variables initialization

You could do it this way:

Features(int F1,int F2,int F3,int F4)
{
    this->F1 = F1;
    this->F2 = F2;
    this->F3 = F3;
    this->F4 = F4;
}

But

Features(int F1,int F2,int F3,int F4)
      : F1(F1), F2(F2), F3(F3), F4(F4) { }

Is preferred, because for user defined types default constructor will invoked automatically and can give you some overhead. In case your member variables do not have default constructor it is necessary to initialize them in initializer list. Constant fields must be initialized in the initializer list as well

And also I think it's just more clear to use initialization lists

Upvotes: 2

Mihai Todor
Mihai Todor

Reputation: 8239

Give this tutorial a read. It should answer your question.

Upvotes: 1

Related Questions