Some basic knowledge of C + +, which is helpful to the interview __c++

Source: Internet
Author: User

http://blog.csdn.net/allen_fan_01/article/details/9713555

1.new, delete, malloc, free relationship

Delete calls the destructor of the object, and the new corresponds, free only frees up memory and new calls the constructor. malloc and free are standard library functions for c++/c languages, and new/delete are the operators of C + +. Both can be used to request dynamic memory and free memory. For objects that are not internal data types, Malloc/free cannot meet the requirements of dynamic objects. Objects are created with the constructor automatically executed, and the destructor is automatically executed before the object dies. Because Malloc/free is a library function and not an operator, it is not possible to impose the task of executing constructors and destructors on Malloc/free without the compiler controlling permissions. The C + + language therefore requires a new operator to complete dynamic memory allocation and initialization, as well as an operator delete that cleans and frees up memory work. Note that New/delete is not a library function. 2.delete differs from delete []

Delete Calls only a destructor, and delete[] invokes the destructor of each member. In more effective C + + There is a more detailed explanation: "When the delete operator is used for an array, it calls the destructor for each array element, and then calls the operator delete to free the memory." "Delete is matched with new, delete [] with new [] matching

MEMTEST*MTEST1=NEWMEMTEST[10];   Memtest*mtest2=newmemtest;   INT*PINT1=NEWINT[10];   Int*pint2=newint;  Delete[]pint1;  -1-delete[]pint2; -2-delete[]mtest1;//-3-delete[]mtest2;//-4-

The error is in the division.

This means that the delete and delete[] features are the same for built-in simple data types . For custom complex data types, delete and delete[] are not interoperable . Delete[] Deletes an array, delete deletes a pointer. In simple terms, the memory allocated with new is deleted with delete, and the memory allocated with new[] is deleted with delete[. delete[] invokes the destructor of the array element . The internal data type does not have a destructor, so the problem is small. If you use delete without parentheses, delete will think that it points to a single object, otherwise it will think that it points to an array. 3.C and C + + have in common. The difference.

C is a process-oriented programming language 
and C + + is an object-oriented programming language! 
C + + On the basis of fully compatible with the English language, the addition of <strong>, reference </strong> and many other concepts, the core of programming from the function to the class 
C language of the main terminology coding system.

4. Advantages and disadvantages of inheritance.

Class inheritance is statically defined at compile time and can be used directly, and class inheritance makes it easier to change the implementation of the parent class. But class inheritance has some drawbacks. First, because inheritance is defined at compile time, the implementation that inherits from the parent class cannot be changed at run time. Worse, the parent class usually defines at least part of the behavior of the subclass, and any changes to the parent class can affect the behavior of the subclass. If the inherited implementation is not appropriate to solve the new problem, the parent class must be overridden or replaced by a more appropriate class. This dependency limits flexibility and ultimately limits reusability. What are the properties of 5.c++ (object-oriented features)

Encapsulation, inheritance, and polymorphism.

In object-oriented programming languages, encapsulation is the use of reusable components to construct software system features, which not only support the reusability of the system, but also improve the scalability of the system; Message passing can implement a common message and invoke a different method; encapsulation is a technique for realizing information concealment, The purpose is to separate the definition and implementation of the class. 6. To invoke the destructor of the parent class when the subclass is destructor.

The order of the destructor calls is to derive the destructor of the base class after the destructor of the class , that is to say, the information of the derived class has been completely destroyed when the destructor of the base class is invoked. The constructor of the base class is called first when an object is defined, and then the constructor of the derived class is called, and the destructor is reversed: The destructor of the derived class is called first, and then the destructor of the base class is called

Java non-destructor deep copy and shallow copy

7. Polymorphic, virtual function, pure virtual function

Polymorphism: A different action occurs when a different object receives the same message.

The polymorphism of C + + is embodied in two aspects of running and compiling :

The polymorphism of the program runtime is embodied by inheritance and virtual function .

At compile-time polymorphism is reflected in the overloads of functions and operators

virtual function: A member function that is called the keyword virtual in a base class. It provides an interface interface. Allows you to redefine the virtual functions of a base class in a derived class.

function of a pure virtual function: Preserve the name of a function for its derived class in the base class so that the derived class defines it as needed. as an interface, there is no function of pure virtual function, which can not be called directly.

A pure virtual function inherited from a base class that is still a virtual function in a derived class. If there is at least one pure virtual function in a class, then this class is called an abstract class .

Abstract classes include not only pure virtual functions, but also virtual functions. an abstract class must be used as a base class for deriving other classes, not for creating object instances directly .

However, you can still support run-time polymorphism with pointers to abstract classes. 8. Find the return value of the following function (Microsoft)

int func (x)
{
int countx = 0;
while (x)
{
Countx + +;
x = x& (x-1);
}
return countx;
}

Suppose x = 9999. Answer: 8

Train of thought: Convert X to 2 to see the number of 1 contained . 9. What is a "reference". The issues to be noted and the use of references.

A: A reference is the alias of a target variable, and the action applied is exactly the same as the direct manipulation of the variable.

when you declare a reference, remember to initialize it . After the reference declaration is complete, it is equivalent to the target variable name with two names , that is, the target's original name and reference name, and the reference name cannot be used as an alias for another variable name. Declaring a reference, not a newly defined variable, only indicates that the reference name is an alias of the target variable name, it is not a data type itself, so the reference itself does not occupy the storage unit and the system does not allocate the storage unit to the reference . cannot establish a reference to an array . 10. What are the characteristics of a "reference" as a function parameter?

(1) The effect of passing a reference to a function is the same as passing a pointer . At this time, the parameter of the function is called the real parametric or an alias of the object in the original keynote function, so the operation of the parameter variable in the modulated function is the operation of its corresponding target object (in the keynote function).

(2) using the parameters of the reference pass function, there is no copy of the argument in memory, it is directly to the argument, but the parameter of the function is passed by the general variable, when the function is called, the parameter is allocated to the memory unit, and the parameter variable is a copy of the argument variable; If the object is passed, The copy constructor is also invoked. Therefore, when the parameter passes the data is big, uses the reference to pass the parameter with the general variable the efficiency and occupies the space to be good.

(3) The use of pointers as a function of the parameters, although also can achieve the effect of using references, however, it is very easy to make errors and poor reading of programs in the same way that the parameters are allocated to the parameters of the function, and the "* pointer variable name" needs to be used repeatedly. On the other hand, at the call point of the calling function, you must use the address of the variable as the argument . And references are easier to use and clearer. 11. When you need to use the "constant reference".

If you want to use the reference to improve the efficiency of the program, but also protect the data passed to the function is not changed in the function, you should use the constant reference.

Constant reference declaration method: Const type identifier & reference name = target variable name;

Example 1

int A;
const INT &ra=a;
Ra=1; Error
A=1; That's right

Example 2

string foo ();
void Bar (string & S);

Then the following expression will be illegal:

Bar (foo ());
Bar ("Hello World");

The reason is that Foo () and the "Hello World" string all produce a temporary object, whereas in C + + These temporary objects are const types. So the expression above is an illegal attempt to convert a const-type object to a non-const type. reference parameters should be defined as const if they can be defined as const. 12. Use "Reference" as a function return value type format, benefits, and rules to follow?

Format: type identifier & function name (parameter list and type description) {//function body}

Benefit: No copy of the returned value is generated in memory; (note: For this reason, it is undesirable to return a reference to a local variable.) Because with the end of the local variable lifetime, the corresponding reference is invalidated, resulting in runtime error!

Precautions:

(1) a reference to a local variable cannot be returned . This can refer to item 31 of effective c++[1]. The main reason is that local variables are destroyed after the function returns, so the returned reference becomes a reference to "no references" and the program goes into an unknown state.

(2) cannot return a reference to the memory allocated by the function's internal new . This can refer to item 31 of effective c++[1]. Although there is no problem of passive destruction of local variables, it can be faced with other embarrassing situations in this case (returning the reference of allocating memory within new function). For example, a reference returned by a function only appears as a temporary variable without being given an actual variable, so the space that the reference points to (allocated by new) cannot be released, causing memory leak.

(3) You can return a reference to a class member, but preferably a const. This principle can refer to item 30 of effective c++[1]. The main reason is that when an object's properties are associated with a certain business rule (business rules), the assignment is often related to the state of some other property or object, so it is necessary to encapsulate the assignment operation in one business rule. If other objects can get a very strong reference (or pointer) to the property, then a simple assignment to that property can break the integrity of the business rule.

(4) the function of the overload return value of the stream operator is declared as "reference" :

Stream operators << and >>, these two operators often want to be used continuously, for example: cout << "Hello" << Endl; So the return value of these two operators should be a stream reference that still supports both operators. Alternative alternatives include: returning a Stream object and returning a stream object pointer. But for returning a stream object, the program must recreate (copy) a new stream object, that is, the continuous two << operators are actually for different objects. It's not acceptable. The << operator cannot be used continuously for returning a stream pointer. Therefore, returning a Stream object reference is the only choice . The only option is critical, which illustrates the importance and irreplaceable nature of references, and perhaps that's why the concept of referencing is introduced in the C + + language. Assignment operator =. This operation, like the Fuchang operator, can be used continuously, for example: x = j = 10; or (x=10) = 100; The return value of the assignment operator must be a left value so that it can be continued to be assigned. So the reference is the only return value selection for this operator.

Example 3

#i nclude <iostream.h>
int &put (int n);
int vals[10];
int error=-1;
void Main ()
{
Put (0) = 10; The put (0) function value as the left value is equivalent to vals[0]=10;
Put (9) = 20; The put (9) function value as the left value is equivalent to vals[9]=20;
cout<<vals[0];
cout<<vals[9];
}
int &put (int n)
{
if (n>=0 && n<=9) return vals[n];
else {cout<< "subscript error"; return error;}
}

(5) In some other operators, but must not return the reference:+-*/arithmetic character. They cannot return the reference , effective c++[1] 's ITEM23 discusses the issue in detail. The main reason is that these four operators do not have side effect, so they must construct an object as the return value , and the optional scheme includes: Returning an object, returning a reference to a local variable, returning a reference to a new assigned object, and returning a static object reference. The 2nd and 32 scenarios have been deprecated, based on the three rules referred to above as the return value. A reference to a static object also causes an error because ((a+b) = = (C+d)) will always be true. So the only option left is to return one object. 13. The relationship between "reference" and polymorphism.

A reference is another means of producing a polymorphic effect, other than a pointer. This means that a reference to a base class can point to its derived class instance.

Example 4

Class A;  Class b:class a{...}; b b; a& ref = B; 14. What is the difference between a "reference" and a pointer?

When the pointer points to an object through a pointer variable, it indirectly operates on the variable it points to. The use of pointers in programs, the readability of the program is poor, and the reference itself is the alias of the target variable, the operation of the reference is the operation of the target variable. In addition, this is the difference between the function ref and pointer mentioned above. 15. When do I need to "quote"?

References are recommended for flow operators << and >>, the return value of the assignment operator =, the parameters of the copy constructor, the parameters of the assignment operator =, and others. Http://develop.csai.cn/c/NO0000021.htm 16. Structure and union have and difference.

(1). Structs and unions are composed of several different data type members, but at any one time the union holds only a selected member (all members share a single address space), and all members of the structure exist (the different members have different hosting addresses).
(2). The assignment of different members of the Union will be overridden for other members, and the value of the original member does not exist , and the assignment of different members of the struct does not affect each other. 17. The output of the topic about "union".

A

#i nclude <stdio.h>
Union
{
int i;
Char x[2];
}a;

void Main ()
{
A.x[0] = 10;
A.X[1] = 1;
printf ("%d", A.I);
}
Answer: int accounts for 4 bytes, X is 2 bytes, memory is aligned, and the total size is 4 bytes. Save 10 (ie 0A), then save 1 (ie 01),

Memory footprint is ox 0a,i that is 0x010a, the conversion result is: 1x16^2+10 = 266

(Low lower address, high address)

b

Main ()
{
union{/* Defines a joint * *
int i;
struct{/* Define a structure in the union * *
Char A;
char second;
}half;
}number;
number.i=0x4241; /* Union member Assignment * *
printf ("%c%cn", Number.half.first, Mumber.half.second);
Number.half.first= ' a '; /* The struct member assignment in the union * *
Number.half.second= ' B ';
printf ("%xn", number.i);
Getch ();
}
Answer: First deposit half, second, memory in the case is: Second-first ("-" to show the difference)

AB (0x41 corresponds to ' A ', is low; Ox42 corresponds to ' B ', is high)

6261 (NUMBER.I and Number.half share an address space) 18. Correlation, Aggregation (Aggregation), and combination (composition) differences.

It involves some concepts in UML: Association is a general relationship between two classes, such as "student" and "teacher" is an association; aggregation represents has-a relationships, a relatively loose relationship in which aggregation classes do not need to be held accountable for aggregated classes, as shown in the following illustration, To represent an aggregation relationship with an empty diamond: from an implementation perspective, aggregations can be represented as:

Class A {...} Class B {A * A;.}

The combination of the contains-a relationship is stronger than the aggregation: The combination class has the same life cycle as the grouped class, and the combined class is responsible for the grouped class, with a solid diamond representation combination: The form is:

Class a{...} class b{A;.}

Add: reference:http://blog.bandao.cn/archive/35755/blogs-679502.aspx

Five kinds of relationships in UML

<1> Dependence

Dependencies are represented by dotted lines and arrows, as shown in the figure:

The above figure says: The animal class relies on the water class (animals depend on water).

Dependence is the least coupled relationship between the five relationships of a class. Because the dependencies are generated by the code, the two relational classes do not add attributes.

This weak relationship can be explained by the degree of mutual understanding between classes. (The following illustration is a code generation diagram)

The water class is not added to the properties of the animal class in the generated code that is visible from the figure above. So how do animal classes use water classes, there are three ways: the three forms of dependency:

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.