Aggregate type and value Initialization

Source: Internet
Author: User
Introduction

In C ++, pod is an extremely important concept. To understand the pod type, we must first understand the aggregate type. According to the answer in stackoverflow, we will give a comprehensive explanation of the aggregate type.

Definition of aggragates

C ++ standard (C ++ 03 8.5.1§ 1:

An aggregate is an array or a class (Clause 9) with no user-declared Constructors (12.1), no private or protected non-static data members (clause 11 ), no base classes (clause 10), and no virtual functions (10.3 ).

A Aggregate is an array or a non-static data member with no user-declared constructor, no private or protected type, and no parent class or virtual function type.

In the definition, we can first interpret the following information:

1. the array must be aggregate.

2. The class that meets the following definitions can also be aggregate (Note: The class includes classes, structs, and unions ):

->Aggregate cannot have user-defined constructors.In fact, it can have a default constructor or a default replication constructor, as long as they are declared by the compiler, rather than customized.

->Aggregate cannot have private or protected non-static data members.In fact, you can define other private and protected member methods (not including constructors. For aggregate, user-defined constructors are not supported. See the previous article ), you can also define private and protected static data members and methods, which do not violate the aggregate type rules.

->Aggregate does not have a parent class or virtual function.

-> The aggregate type can be user-defined assignment operators and destructor.

Note: The array must be of the aggregate type, even if the array contains non-aggregate elements.

Example
class NotAggregate1{  virtual void f(){} //remember? no virtual functions};class NotAggregate2{  int x; //x is private by default and non-static };class NotAggregate3{  public:  NotAggregate3(int) {} //oops, user-defined constructor};class Aggregate1{  public:  NotAggregate1 member1;   //ok, public member  Aggregate1& operator = (Aggregate1 const & rhs) {/* */} //ok, copy-assignment    private:  void f() {} // ok, just a private function};
Why AggregatesAre special?

Different from non-aggregate types,The aggregate type can be initialized using "{}".. This initialization syntax is actually very common in arrays. Don't forget that our array type also belongs to aggregate. Let's take a look at the following example:

Type array_name[n] = {a1, a2, ..., am};

1. If M is equal to N: Naturally, the I-th element of the array is initialized to AI.

2. If M is less than N: The first M elements of the array are initialized as A1, A2 ,..., AM, the remaining N-M elements will be initialized (provided that the value can be initialized ).

3. If M is greater than N, a compilation error is generated.

Note that the format similar to the following is correct:

Int A [] = {1, 2, 3};) // equivalent to int A [3] = {1, 2, 3 };

The length of the array is estimated to be 3 by the compiler, so the above two forms are equivalent.

Value initialization ( Value-initialization)

Let's take a look at the following explanation from stackoverflow:

When an object of scalar type (bool,int,char,double, Pointers, etc.) isValue-initializedIt means it is initialized0For that type (falseForbool,0.0Fordouble, Etc .). when an object of class type with a user-declared default constructor is value-initialized its default constructor is called. if the default constructor is implicitly defined then all nonstatic members are recursively value-initialized. this definition is imprecise and a bit incorrect but it shoshould give you the basic idea. A reference cannot be value-initialized. value-initialization for a non-aggregate class can fail if, for example, the class has no appropriate default constructor.

The translation is as follows:

If an object of scalar type (such as bool, Int, Char, double, pointer) is initialized by value, it is initialized to 0 (for example: the bool type is initialized to false, and the double type is initialized to 0.0 ).

If the default constructor is initialized by value, the default constructor is called. If the default constructor is implicitly defined, all non-static data members will recursively initialize by value.

Although the above definition is not accurate or complete, we can have a basic understanding.Note that references cannot be initialized by value. Initialization of values for non-aggregate classes may fail. For example, there is no suitable default constructor.

1. Here is an example of array initialization:

Class A () {A (INT) {}// the User-Defined constructor is not of the aggrerate type. Note that Class A does not have a default constructor. Class B () {B () {} // the User-Defined constructor is not of the aggrerate type. Note that Class B has available Default constructors. You can initialize a value when defining an object. }; Int main () {A A1 [3] = {A (2), a (1), a (14 )}; // OK n = m a A2 [3] = {A (2)}; // error A does not have a default constructor. you Cannot initialize A2 [1] and A2 [2] B B1 [3] = {B ()} by value ()}; // OK B1 [1] and B1 [2] use the default constructor to initialize int array1 [1000] = {0} by value }; // all elements are initialized as 0 int array2 [1000] = {1}; // Note: only the first element is initialized as 1, and the others are initialized as 0; bool array3 [1000] ={}; // the braces can be empty. All elements are initialized to false; int array4 [1000]; // not initialized. this is different from null {} initialization. In this case, elements are not initialized by value. Their values are unknown and uncertain; (unless array4 is global data) int arr Ay [2] = {1, 2, 3, 4}; // error, too many initial values, compilation error .}

2. Now let's take a look at how the aggregates class type is initialized using. It is very similar to initializing an array. It initializes non-static member variables in the order declared inside the class (which must be public by definition. If the initial value is less than the Member value, other members will be initialized by value. If one member cannot perform value-based initialization, we will get a compilation error. If the initial value is more than the Member value, we also get a compilation error.

struct X{  int i1;  int i2;};
struct Y{  char c;  X x;  int i[2];  float f; 
protected:  static double d;
private:  void g(){}      }; Y y = {‘a‘, {10,20}, {20,30}};

In the above example, Y. C is initialized to 'A', Y. x. i1 is initialized to 10, Y. x. i2 is initialized to 20, Y. I [0] is 20, Y. I [1] is 30, Y. f is initialized to 0.0 by value. The static data member D of the protected type is not initialized because it is static. Summary

We understand the special characteristics of aggregates. Now let's try to understand its type restrictions, that is, why are these restrictions. The following explanation is also taken from stackoverflow:

We shoshould understand that memberwise initialization with braces implies that the class is nothing more than the sum of its members. if a user-defined constructor is present, it means that the user needs to do some extra work to initialize the members therefore brace initialization wocould be incorrect. if virtual functions are present, it means that the objects of this class have (on most implementations) a pointer to the so-called vtable of the class, which is set in the constructor, so brace-initialization wocould be insufficient. you cocould figure out the rest of the restrictions in a similar manner as an exercise :)

We should understand that using {} to initialize members one by one means that this type is only a set of members.

If there is a user-defined constructor, it means that the user needs to do some extra work to initialize the members, so using {} for initialization is incorrect. If there is a virtual function, it means that this type (most implementations) has a pointer to vtable and needs to be set in the constructor. Therefore, using {} for initialization is not enough. We can understand the meaning of other restrictions in this way.

In the next blog, we will introduce the pod (native data type) through the aggregates type ). References

1. What are aggregates and pods and how/why are they special?

Aggregate type and value Initialization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.