Basic C ++ interview questions

Source: Internet
Author: User

1. What is "reference "? What should I pay attention to when declaring and using "reference?

A: A reference is the "alias" (alias) of a target variable. operations on an application are identical to operations on a variable. When declaring a reference, remember to initialize it. After the reference declaration is complete, the target variable name has two names, that is, the original name and reference name of the target, and the reference name cannot be used as the alias of other variable names. Declaring a reference is not a new variable. It only indicates that the reference name is an alias of the target variable name. It is not a data type, so the reference itself does not occupy the storage unit, the system does not allocate storage units to references. You cannot create an array reference.

2. What are the features of using "Reference" as a function parameter?

(1) passing a reference to a function has the same effect as passing a pointer. In this case, the parameter of the called function becomes an actual parameter variable or an alias of the object in the original main function, therefore, the operations on the parameters in the called function are the operations on the corresponding target object (in the main function.

(2) using the reference parameter to pass the function does not generate a copy of the real parameter in the memory, it is directly to operate on the real parameter; while using the general variable to pass the function parameter, when a function call occurs, you need to allocate storage units to the parameters. The parameters are copies of the real variables. if the object is passed, the copy constructor will also be called. Therefore, when the data transmitted by a parameter is large, it is better to use reference than to transmit a parameter using a common variable.

(3) Although using pointers as function parameters can achieve the same effect as using references, in the called function, storage units must be allocated to the parameters, the "* pointer variable name" format must be used repeatedly for calculation, which can easily lead to errors and the program reading is poor. On the other hand, at the call point of the main function, the variable address must be used as the real parameter. References are easier to use and clearer.

3. When do I need to use "regular reference "?

If you want to use references to improve program efficiency and protect the data transmitted to the function from being changed in the function, you should use regular references. Common Reference declaration method: const type identifier & reference name = target variable name;

Example 1

Int;
Const Int & RA =;
Ra = 1; // Error
A = 1; // correct

Example 2

String Foo ();
Void bar (string & S );

The following expression is invalid:

Bar (FOO ());
Bar ("Hello World ");

The reason is that both the Foo () and "Hello World" strings generate a temporary object. In C ++, these temporary objects are of the const type. Therefore, the above expression tries to convert a const type object to a non-const type, which is invalid.

The referenced parameter should be defined as const if it can be defined as Const.

4. Use "Reference" as the format, benefits, and rules of the function return value type?

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

Benefit: do not generate a copy of the returned value in the memory. (Note: For this reason, it is not advisable to return a reference to a local variable. As the survival of the local variable ends, the corresponding reference will also become invalid, resulting in a runtime error!

Note:

(1) References to local variables cannot be returned. For more information, see valid tive.
Item 31 of C ++ [1. the main reason is that local variables will be destroyed after the function returns, so the returned reference becomes a reference of "no finger", and the program enters the unknown state.

(2) You cannot return a reference to the memory allocated by the new function. For details, refer to item 31 of Objective C ++ [1. although there is no passive destruction of local variables, this situation (returning a reference to the memory allocated by the new function) faces other embarrassing situations. For example, if a reference returned by a function only appears as a temporary variable and is not assigned to an actual variable, the space pointed to by the reference (allocated by new) cannot be released, cause memory leak.

(3) can return the reference of the class member, but it is better to be const. this principle can be referred to item 30 of Objective C ++ [1. the main reason is that when an object attribute is associated with a business rule, its value assignment is often related to some other attributes or the state of the object, therefore, it is necessary to encapsulate the value assignment operation in a business rule. If other objects can obtain the non-constant reference (or pointer) of this attribute, a simple value assignment to this attribute will damage the integrity of business rules.

(4) The function of declaring the returned value of stream operator overload as "Reference:

Stream operators <and>, which are often used consecutively, for example, cout <"hello" <Endl; therefore, the return value of these two operators should be a stream reference that still supports these two operators. Other optional solutions include returning a stream object and returning a stream object pointer. However, for a returned Stream object, the program must re-(copy) to construct a new stream object. That is to say, two consecutive <operators are actually for different objects! This is unacceptable. If a stream pointer is returned, the <operator cannot be used consecutively. Therefore, returning a stream object reference is the only choice. This unique choice is critical. It illustrates the importance of reference and is irreplaceable. Maybe this is why the concept is introduced in C ++. Value assignment operator =. This operator can be used continuously like a stream operator, for example, X
= J = 10; or (x = 10) = 100; the return value of the value assignment operator must be a left value so that the value can be assigned. Therefore, it is referenced as the only return value choice of this operator.

Example 3

# I nclude <iostream. h>
Int & put (int n );
Int Vals [10];
Int error =-1;
Void main ()
{
Put (0) = 10; // use the put (0) function value as the left value, equivalent to Vals [0] = 10;
Put (9) = 20; // use the put (9) function value as the left value, which 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) among other operators, the reference: +-*/four Arithmetic Operators cannot be returned. They cannot return references. The Objective C ++ [1] item23 discusses this issue in detail. The main reason is that these four operators do not have side effect. Therefore, they must construct an object as the return value. Optional solutions include: returning an object and returning a reference to a local variable, returns the reference of a newly assigned object and a static object reference. According to the preceding three rules that reference the returned value, both the 2nd and 3 schemes are rejected. Static object reference is caused by errors because (a + B) = (C + D) is always true. Therefore, only one object is returned.

5. What is the relationship between "reference" and polymorphism?

References are another method that can produce polymorphism effects except pointers. This means that a base class reference can point to its derived class instance.

Example 4

Class A; Class B: Class A {...}; B; A & ref = B;

6. What is the difference between "reference" and pointer?

After a pointer variable points to an object, it indirectly operates on the variable it points. When pointers are used in a program, the program has poor readability. The reference itself is the alias of the target variable, and the reference operation is the operation of the target variable. In addition, it is the difference between the ref passed to the function and the pointer mentioned above.

7. When do I need to "Reference "?

Stream operators <and>, return values of the value assignment operator =, parameters of the copy constructor, parameters of the value assignment operator =, and references are recommended in other cases.

8. What is the function of ifndef/define/endif in the header file?

A: prevent this header file from being repeatedly referenced.

9. # What is the difference between I nclude <file. h> and # I nclude "file. H?

A: The former searches for and references file. h from the standard library path, and the latter searches for and references file. h.

10. What are the three basic features of object-oriented architecture?

11. encapsulation: Abstract Objective objects into classes. Each class implements protection (private, protected, public) on its own data and methods)

12. inheritance: generalized inheritance has three implementation forms: Implementation inheritance (the ability to use the attributes and methods of the base class without additional encoding) visual inheritance (child forms use the appearance and implementation code of the parent form) and interface inheritance (only properties and methods are used to implement sub-classes ). The first two methods (class inheritance) and the last one (Object combination => interface inheritance and pure virtual functions) constitute two methods of function reuse.

13. polymorphism: a technology that sets a parent object to be equal to one or more other sub-objects, the parent object can operate in different ways based on the features of the sub-objects assigned to it. To put it simply, you can assign a pointer of the subclass type to a pointer of the parent class.

14. What is the difference between overload and overried?

Common Questions. In terms of definition:

Overload: multiple functions with the same name are allowed, and the parameter tables of these functions are different (maybe the number of parameters is different, maybe the parameter types are different, or both are different ).

Rewrite: it refers to the method for the subclass to redefine the complex class virtual function.

In terms of implementation principle:

Overload: the compiler modifies the names of functions with the same name based on different parameter tables of the function, and then these functions with the same name become different functions (at least for the compiler ). For example, there are two functions with the same name: function func (P: integer): integer; and function func (P: string): integer ;. The modified function names of the compiler may be like this: int_func and str_func. The call to these two functions has been confirmed between the compilers and is static. That is to say, their addresses are bound during compilation (early binding). Therefore, overloading is irrelevant to polymorphism!

Rewriting: It is really related to polymorphism. When the subclass redefined the virtual function of the parent class, the parent class pointer dynamically calls the function of the subclass according to the different subclass pointer assigned to it, such a function call cannot be determined during compilation (the virtual function address of the called subclass cannot be provided ). Therefore, such function addresses are bound at runtime (late binding ).

15. What is the role of polymorphism?

There are two main types: 1. hide implementation details to modularize the code. Expand the code module to reuse the code. 2. interface reuse: This ensures that a class is called correctly when using a certain attribute of an instance of any class in the family during class inheritance and derivation.

16. What are the relationships and differences between New Delete and malloc free?

Answer: all are dynamic memory operations on heap. To use the malloc function, you must specify the number of bytes allocated by the memory and Cannot initialize the object. New automatically calls the object constructor. Delete calls the destructor of the object, but free does not call the destructor of the object.

17. # define double (x) x + X, I = 5 * double (5); what is I?

Answer: I am 30.

18. In which situations can I use the intialization list instead of the assignment?

Answer: when the class contains const and reference member variables, the base class constructors need to initialize the table.

19. Is C ++ type-safe?

Answer: No. Two different types of pointers can be forcibly converted (reinterpret cast ). C # is type-safe.

20. What code will be executed before the main function is executed?

Answer: The constructor of the global object is executed before the main function.

21. describes the memory allocation methods and their differences?

1) distributed from the static storage area. The program has been allocated when it is compiled, and the program exists throughout the entire runtime. For example, global variables and static variables.

2) create a stack. When a function is executed, the storage units of local variables in the function can be created on the stack. When the function is executed, these storage units are automatically released. Stack memory allocation operations are embedded in the processor's instruction set.

3) distributed from the stack, also known as dynamic memory allocation. When the program runs, it uses malloc or new to apply for any amount of memory. The programmer is responsible for releasing the memory with free or delete. The lifetime of the dynamic memory is determined by the programmer. It is very flexible to use, but the problem is also the most.

22. Difference Between struct and class

Answer: struct members are public by default, while Class Members are private by default. Struct and class are quite functional in other aspects.

Emotionally, most developers feel that classes and structures are very different. It seems that the structure is just like a bunch of open memory spaces that lack encapsulation and functionality, and the class is like a living and reliable social member. It has smart services, it has a strong encapsulation barrier and a well-defined interface. Since most people think so, there are only a few methods in your class and public data (this kind of thing exists in a well-designed system !) You should use the struct keyword. Otherwise, you should use the class keyword.

23. When a Class A does not have any member variables and member functions, what is the value of sizeof (a)? If it is not zero, explain why the compiler didn't make it zero. (Autodesk)

Answer: it must not be zero. For example, if it is zero, declare an array of Class A [10] objects, and each object occupies zero space. In this case, a [0] cannot be distinguished. A [1]… .

24. How is the logical and physical addresses converted in the 8086 assembly? (Intel)

Answer: The address provided by the general register is the intra-range offset address. The corresponding segment register address * 10 h + the intra-range address in the General Register gets the address to be accessed.

25. How do I compare the four types of conversion methods in C ++?

For details, refer to the differences and Applications of role, dynamic_cast and reinterpret_cast.

26. Write the comparison statements of Boolean, Int, float, and pointer type variables A and zero respectively.

Answer:

Bool: If (! A) or if ()
INT: if (a = 0)
Float: const expressions exp = 0.000001
If (A <exp & A>-exp)
Pointer: if (! = NULL) or if (a = NULL)

27. What are the advantages of const compared with # define?

Answer:

1) const constants have data types, while macro constants do not. The compiler can perform type security checks on the former. However, only character replacement is performed for the latter, and there is no type security check, and unexpected errors may occur during character replacement.

2) some integrated debugging tools can debug const constants, but cannot debug macro constants.

28. What are the differences between arrays and pointers?

An array is either created in a static storage area (such as a global array) or on a stack. Pointers can point to any type of memory block at any time.

(1) Differences in modification content
Char A [] = "hello ";
A [0] = 'X ';
Char * P = "world"; // note that P points to a constant string
P [0] = 'X'; // This error cannot be found by the compiler. It is a runtime error.
(2) the sizeof operator can be used to calculate the array capacity (number of bytes ). Sizeof (P), P is the number of bytes of a pointer variable, rather than the memory capacity referred to by P. C ++/C language cannot know the memory capacity referred to by the pointer unless you remember it when applying for memory. Note: When an array is passed as a function parameter, the array will automatically degrade to a pointer of the same type.
Char A [] = "Hello World ";
Char * P =;
Cout <sizeof (a) <Endl; // 12 bytes
Cout <sizeof (p) <Endl; // 4 bytes
Calculate the memory size of arrays and pointers
Void func (char a [1, 100])
{
Cout <sizeof (a) <Endl; // 4 bytes instead of 100 bytes
}

29. What are the differences between Overloading, overwriting, and hiding of class member functions?

Answer:

A. Features of member functions being overloaded:

(1) the same range (in the same class );

(2) The function name is the same;

(3) parameters are different;

(4) virtual keywords are optional.

B. Override refers to the function of the derived class that overwrites the base class function. The features are as follows:

(1) different scopes (located in the derived class and the base class respectively );

(2) The function name is the same;

(3) The parameters are the same;

(4) basic functions must have virtual keywords.

C. "hide" means that the function of the derived class shields the base class functions with the same name as it. The rules are as follows:

(1) If the function of the derived class has the same name as the function of the base class, but the parameter is different. In this case, functions of the base class will be hidden regardless of whether there is any virtual keyword (Be sure not to confuse them with overload ).

(2) If the function of the derived class has the same name and parameter as the function of the base class, but the base class function does not have the virtual keyword. At this time, the base class functions are hidden (Be sure not to confuse with overwrite)

30. There are two int variables: A and B, don't use "if", "? : "," Switch "or other judgement statements, find out the biggest one of the two numbers.

Answer: (a + B) + ABS (a-B)/2

31. Multi-inheritance memory allocation problem: for example, if there is Class A: Public Class B, public class c {}, what is the memory structure of?

This is compiler-dependent. Different implementations may have different details.

If you do not consider virtual functions or virtual inheritance, it is quite simple; otherwise, it is quite complicated.

You can refer to exploring the C ++ Object Model in depth, or:

32. Does a parent class write a virtual function? Can a sub-class overwrite its function without the virtual function realize polymorphism?

Virtual modifiers are implicitly inherited. Private is also integrated, but the derived class has no access permission. Virtual instances can be added or not added. All variables of the parent class (except static) exist in the space of the Child class ).

33. Const symbolic constant;
(1) const char * P
(2) Char const * P
(3) char * const P
The differences described above are described;

If the const is on the left side of the asterisk, the const is used to modify the variable pointed to by the pointer, that is, the pointer points to a constant;
If const is on the right side of the asterisk, const modifies the pointer itself, that is, the pointer itself is a constant.

Const char * P; // same as char const * P

Char const * P; // pointer to a constant. The constant value cannot be changed.

Char * const P; // constant pointer. The value of P cannot be modified.

34. What is the problem with the following code?
Void dosomething (...)
{
Char * P;
...
P = malloc (1024); // allocate 1 K space
If (null = P)
Return;
...
P = realloc (p, 2048); // The space is not enough and is allocated to 2 k again.
If (null = P)
Return;
...
}

A:
P = malloc (1024); It should be written as: P = (char *) malloc (1024 );
No space for P is released, causing memory leakage.

35.

The following function adds a number to a fixed number. If any errors occur, correct them.
Int add_n (int n)
{
Static int I = 100;
I + = N;
Return I;
}

A:
Because static makes the I value retain the previous value.
Remove static.

Source: the original article is from the Internet.

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.