Comparison between C ++ and C #: class initialization

Source: Internet
Author: User
Class and Plato's concept world

We know that object-oriented programming is full of classes, but classes are just conceptual, not entities, and do not occupy memory. You cannot use them until they are instantiated. A class is a real entity only after it is instantiated into an object. memory occupied, which can be used by us. classes are a bit like the world of ideas mentioned by Plato. Plato believes that there are two worlds. One is the real world in which we live, and the opposite is the world of ideas, what is the concept world? It is an everlasting world, composed of a pile of ideas, such as people, horses, birds .... the concept of people is just a concept, not any actual person. in our real world, we simulate people and horses based on ideas. some people may simulate pretty, so there are handsome guys, some are failed products, so there are also a large number of dinosaur frogs. who did the simulated action? Plato did not say. Some people think that God is doing this.

Then, when instantiating a class, it is a bit like the work of God. From the concept world, we get an empty idea, and then use a constructor instance to convert it into objects one by one.

 

C # class initialization

 

When instantiating a class, we generally use a New Keyword such as myclass Arwen = new myclass (). this is quite similar to C ++. c ++ can instantiate the class to open a memory in heap to save an object. release the memory after it is used up. however, you can also directly use myclass weiwen to save objects in the stack, but the allocation and revocation of the stack are controlled by the system. C # You can only use new to open up the memory option in heap, and the memory in heap is managed by CRL and released for you after it is used up. Therefore, the heap here is called a managed heap.

During class instantiation, we simply used a new one, but in fact there were many other operations in the background. What did we do? We did the following in order:

1. initialize static variables in the class

2. Call the static constructor in the class

3. initialize non-static variables

4. initialize static variables in the parent class

5. Call the static constructor of the parent class

6. initialize non-static variables of the parent class

7. Call the parent class Constructor

8. Call your own Constructor

 

Of course, if you do not inherit a parent class, you don't have to worry about the parent class. if the parent class also inherits a parent class, the parent class inherits from the previous operation. let's take a simple example. if there is a parent father, sub-class son

 

Class father

{

Public static int age; // 4. The value is 0.

Public string name; // 6. The value is null.

Public father () // 7. Call this Constructor

{

Console. writeline ("I Am a lazy father construtor, don't do anything .");

}

Public father (string myname)

{

Console. writeline ("I Am a diligent father constructor .");

Name = myname;

}

Static father () // 5. The value of age is 110.

{

Age = 110;

Console. writeline ("Father static construtor will never do anyting after setting age with a value 110 .");

}

}

 

 

Class son: Father

{

Public static int age; // 1. The initialization age is 0.

Public string name; // 3. The Initialization is null.

Public son ()

{

Console. writeline ("I Am a lazy son construtor, don't do anything .");

}

Public son (string myname) // 8. Call this Constructor

{

Console. writeline ("I Am a diligent son construtor .");

Name = myname;

}

Static son () // 2. Assign age to 11

{

Age = 11;

Console. writeline ("Son static construtor will never do anyting after setting age with a value 11 .");

}

}

 

We instantiate son class.

Son Arwen = new son ("Arwen ");

The output result is

Son static construtor will never do anyting after setting age with a value 11 // class static Constructor

Father static construtor will never do anyting after setting age with a value 110. // The parent class static Constructor

I am a lazy father construtor, don't do anything. // The parent class constructor.

I am a diligent son construtor // class Constructor

 

The execution sequence is based on the eight steps, but there are some points to note.

1 .) the definition of static structures can only be static and class names, but cannot have parameters or any modifiers such as public. you can only assign values to static variables, but not to common fields. Static constructors are called only once when the class is first instantiated. it will not be called when the class is instantiated later. it can only be called by default and cannot be displayed. in addition to the class will be called during the first instantiation, the class will also be called before the first use of static variables in the class. for example, you directly call

Console. writeline (son. Age); print the result

Son static construtor will never do anyting after setting age with a value 11

11

In addition, although the fields of the const type are static by default, if you call the const field, the static constructor still does not execute.

2 .) if there are many constructor functions in the class, no matter which one you use to instantiate the class, the constructor of the parent class will only call the one without parameters. therefore, if you do not have a constructor without parameters and you have a constructor with parameters, you are also the parent class of a class. this will cause errors during compilation. if you don't have any constructor, it's okay. because if you do not have any constructor, the system will generate one by default for you. however, if you write any constructor with or without parameters, the system will not generate it for you by default.

3 .) if you want to call a constructor with parameters of the parent class, this parameter must be specified. use the keyword base. for example, when son calls a constructor with parameters, it also needs to call the constructor with parameters of the parent class at the same time, as shown below:

Public son (string myname): Base (myname)

{

Console. writeline ("I Am a diligent son construtor .");

Name = myname;

}

In this way, the non-argument constructor of the parent class will not be called. the one with parameters called. however, although you do not call a non-argument constructor. but you cannot save it. the no-argument constructor must be written.

4 .) we know that if the subclass has a function with the same name as the parent class, the function of the parent class will be hidden. fields with the same name are also hidden. as shown in my example. there will be a warning during compilation, and you will be reminded to add a new keyword.

New public static int age;

New public string name;

If it is changed to the above, there will be no warning. But it looks strange. In fact, the effect will be the same without new. New is added by default, but it is better to add new explicitly.

 

C ++ class initialization

 

There is no static constructor in C ++. the Order and method of calling constructor are the same as that of C. only the constructors of the parent class are written differently. replace base in C # With the class name of the parent class.

In addition, the static variable members of C ++ and C # Are used differently. initialization is not performed by default during class instantiation. it must be initialized outside the class. in C ++, member variables except for the const static type can be assigned values at the time of declaration, but none of them can be used.

Class father

{

Public:

Static int age;

String name;

Father ()

{

Cout <"I Am a lazy father constructor, don't do anything." <Endl;

}

Father (string myname)

{

Cout <"I Am a diligent father constructor." <Endl;

Name = myname;

}

};

 

Class son: Public father

{

Public:

Static int age;

String name;

Son ()

{

Cout <"I Am a lazy son constructor, don't do anything." <Endl;

}

Son (string myname): Father (myname)

{

Cout <"I Am a diligent son constructor." <Endl;

Name = myname;

}

};

 

Int son: age = 110; // The static variable can only be initialized outside the class. An int must be added before the static variable, but not static.

After initialization, You can reference son: Age in other places and change its value directly. For example, Son: age = 911;

 

C # comparison with C ++ Initialization

 

From the above we can see that the usage of the constructor is almost the same. however, C ++ does not have a static constructor. in addition, when the parent class has a parameter constructor is called, the parent class name is directly used without the base keyword.

The main difference between the two is in the initialization class members.

1 .) during C ++ initialization, as long as the memory is allocated according to the class type, no initialization value is assigned to the member variables. the memory occupied by static variables is not included in the class. static variables are stored in the static memory area. in addition, no memory is actually allocated to the static variable when the class is instantiated. the memory is allocated only when the class is initialized.

2 .) in addition, if you define a common public member variable in the class, you will find a value in cout printing when you do not assign a value. however, the value is uncertain, and it may be a very large value. what's going on?

In fact, we applied for a piece of memory, which is not blank. contains content. for example, if you use new to apply for a piece of memory and then delete it, it doesn't mean that the memory is cleared, and there is nothing in it. in fact, I just told the system that this memory is not needed. then, who else applied for this memory, and your content is in it. you can only erase your content after it is assigned a value again.

 

It is naturally dangerous to use a member variable before it is initialized. therefore, Initialization is required. The important work in C ++ is left to the constructor. Because C # is initialized by default, the constructor is not as important as C ++.

 

Supplement

Static variables have similar meanings in C # And C ++. however, the const variable is far behind. in C #, the default const variable is static. the const variable in C ++ is not static. it is actually a bit like readonly in C. const member variables can only be assigned values in constructors. the value can only be assigned to the initialization parameter list. assume that the class son has a member variable const int No. the value can only be assigned in this way.

Son (): No (120)

{

}

 

 

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.