C + + member variables, initialization order of constructors [Goto]

Source: Internet
Author: User

C + + member variables, initialization order of constructors

First, C + + member variable initialization

1, ordinary variables : generally do not consider what the efficiency of the case can be assigned in the constructor. Consider the efficiency that can be done in the initialization list of the re-constructor function

2 Static variables (localized data and code scope):

The static variable belongs to the class and not to the object of the class, so there is only one variable regardless of how many objects the class is instantiated. Understanding in this nature is somewhat analogous to the uniqueness of global variables.

    • The function body, unlike the auto variable, is scoped to the function body, and the variable memory is allocated only once, so its value is maintained the last value on the next call.
    • The static global variable within the module can be accessed by all functions within the module, but not by other functions outside the module.
    • The static function within the module can only be called by other functions within the module, and the application scope of the function is limited to the module in which it is declared.
    • Static member variables in a class are owned by the entire class and have only one copy of all objects of the class.
    • The static member function in a class belongs to the entire class, which does not accept the this pointer, and therefore can only access the static member variables of the class.

3, const constant Volume:

Const constants need to be initialized at the time of declaration. It is therefore necessary to initialize the variable when it is created. Generally used in the initialization list of constructors.

4. Reference Reference variable:

The reference variable is similar to the const variable. It needs to be initialized at the time of creation. is also done in the initialization list. But you need to be careful with the reference type.

5. String initialization

Char str[10] = "HELLO";

The end will be automatically added to the end of the compiler "/0", when compiled can see it finally ", the ASC code value is 0;

"HELLO" is only 5 characters, plus the compiler automatically added '/0 ', which will initialize the first 6 elements of the array, the remaining elements will be all initialized to '/0 ', this should pay attention to OH

Char str[] = "HELLO";

The compiler automatically assigns a size to subsequent strings and adds '/0 '

Char str[] = {' H ', ' E ', ' l ', ' l ', ' O ', '/0 '};

The compiler allocates space based on the size of the string, but does not automatically allocate '/0 ', so add '/0 ' to the end

Char *str = "HELLO";

Give a pointer to a string to a defined character pointer

Second, C + + class initialization

1) Ensure initialization with constructor function

For an empty class, the compiler automatically declares 4 default functions: Constructors, copy constructors, assignment functions, destructors (which should be explicitly rejected if you do not want to use auto-generation), and the resulting functions are public and inline.

2) Why the constructor cannot have a return value

3) Why the constructor cannot be a virtual function

The mechanism of a virtual function call is a function that knows the interface without knowing its exact object type, but creating an object must know the exact type of the object, and one of the first things it does when a constructor is called is to initialize its vptr to point to vtable.

1. Interview questions: Constructors

#include <iostream>
using namespace Std;

Class Base
{
Private
int i;
Public
Base (int x)
{
i = x;
}
};

Class Derived:public Base
{
Private
int i;
Public
Derived (int x, int y)
{
i = x;
}
void print ()
{
cout << i + base::i << Endl;
}
};

int main ()
{
Derived A (2,3);
A.print ();
return 0;
}

First of all, it is the access rights issue, the subclass directly access base::i is not allowed, should change the parent class to protected or public (preferably with protected)

Second, the addition of the parent class and subclass I is counted, but the parent class variable is not initialized by the subclass constructor; The constructor is not found here because the subclass call constructor will first look up the parent class constructor, but there are no 2 arguments, so you can call the parent class constructor in the initialization list

The last problem is the single-parameter constructor, which may have an implicit conversion problem, because the single-argument constructor, like the copy constructor, is likely to be implicitly converted when invoked, plus the explicit keyword

#include <iostream>
using namespace Std;

Class Base
{
Protected
int i;
Public
explicit Base (int x)
{
i = x;
}
};

Class Derived:public Base
{
Private
int i;
Public
Derived (int x, int y): Base (x)
{
i = y;
}
void print ()
{
cout << i + base::i << Endl;
}
};

int main ()
{
Derived A (2,3);
A.print ();
return 0;
}

2. Initialization list

1) Improve efficiency with initialization lists

Class Student
{
Public
Student (string in_name, int in_age)
{
name = In_name;
age = In_age;
}
Private:
String name;
int age;
};

Because in the constructor, the name is assigned, not initialized, and the string object calls its default constructor, and then calls the assignment constructor of the string class (seemingly the Basic_string class), and for the age of the previous example, because int is a built-in type, It should be the value of the assignment when the initial value is obtained.

To initialize a member instead of assigning a value, you can take the initialization list (member initialization lists)

Class Student
{
Public
Student (string in_name, int in_age): Name (In_name), age (In_age) {}
Private:
String name;
int age;
};

The copy constructor of string is called at initialization time, and the two constructors are called by the previous meeting, and there will be no small improvement in performance.

In some cases, it must be initialized with an initialization list: const object, Reference object

2) Initial order of initialization list

#include <iostream>
using namespace Std;

Class Base
{
Public
Base (int i): M_j (i), m_i (M_j) {}
Base (): M_j (0), m_i (M_j) {}
int get_i () const
{
return m_i;
}
int Get_j () const
{
return m_j;
}

Private
int m_i;
int m_j;

};

int main ()
{
Base obj (98);
cout << obj.get_i () << Endl << obj.get_j () << Endl;
return 0;
}

The output is a random number and 98, why? Because the initialization of the member variables for the initialization list is strictly initialized in the order of declaration , not in the initialization list , this problem does not occur if the assignment is initialized instead, of course, In order to use the initialization list, you should pay attention to the order of declarations, such as declaring the array size first, and then declaring the array.

3. C + + constructor initialization is called in the following order:

    • First, the constructors of any virtual base class are constructed in the order in which they are inherited;
    • Second, the constructors of any non-virtual base class are constructed in the order in which they are inherited;
    • Finally, the constructors of any member objects are called in the order in which they are declared;

#include <iostream>
using namespace Std;
Class obj1{
Public
OBJ1 () {cout<< "obj1\n";}
};
Class obj2{
Public
OBJ2 () {cout<< "obj2\n";}
}
Class base1{
Public
Base1 () {cout<< "base1\n";}
}
Class base2{
Public
Base2 () {cout << "base2\n";}
};
Class base3{
Public
Base3 () {cout << "base3\n";}
};
Class base4{
Public
Base4 () {cout << "base4\n";}
};
Class Derived:p ublic Base1, virtual public base2,public Base3, virtual public base4//inheritance order {
Public
Derived (): Base4 (), Base3 (), Base2 (), Base1 (), Obj2 (), obj1 () {//Initialize list
cout << "Derived ok.\n";
}
Protected
OBJ1 obj1;//Declaration Order
OBJ2 Obj2;
};

int main ()
{
Derived aa;//Initialization
cout << "This is ok.\n";
return 0;
}


Results:
BASE2//Virtual base classes are initialized in the order in which they are inherited
BASE4//virtual base classes in the order in which they are inherited
BASE1//non-virtual base classes are initialized in the order in which they are inherited
BASE3//non-virtual base classes in the order in which they are inherited
The OBJ1//member functions are initialized in the order in which they are declared
OBJ2//member functions in the order in which they are declared
Derived OK.
This is OK.

Transferred from: http://www.cnblogs.com/lidabo/p/3628987.html

Related Article

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.