注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

火车的家

Put first thing first

 
 
 

日志

 
 

2017.03.06 c++ interview questions  

2017-03-06 14:48:17|  分类: 技术博客 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
c++ interview questions
1. c++ special member functions
http://www.cplusplus.com/doc/tutorial/classes2/

6. 
Why the constructor is used?
    It is used to initialize the object of that class type during its creation

7.
What is the difference between class and structure?
Structure: Initially (in C) a structure was used to bundle different type of data types together to perform a particular functionality. But C++ extended the structure to contain functions also. The major difference is that all declarations inside a structure are by default public. Class: Class is a successor of Structure. By default all the members inside the class are private.

8. Why the size of empty Class is one byte?
Yes, the compiler will generate 1 byte of memory to mark the existence of the class.  This doesn't answer WHY though.  The reason is the language standard states that all classes must have a memory size of at least 1 byte so that the class doesn't occupy the same memory space with another class.  This is to prevent name mangling.  i.e., if I declare a class A {};, the compiler will still generate an entry in its table to something called "A".  If behind that I declare another class, say class B, if A takes 0 bytes of memory, and B's data gets written in the place where A was declared.  In this case, an instantiation of A would take on the properties of B. 

9. How many levels of pointers can you have?
as many as you want

10.What is a void pointer?
A void pointer is a C convention for "a raw address." The compiler has no idea what type of object a void pointer "really points to." 

11. When is a void pointer used?
A void pointer is used for working with raw memory or for passing a pointer to an unspecified type.
memcpy

12. Can you subtract pointers from each other? Why would you?
If you have two pointers into the same array, you can subtract them. The answer is the number of elements between the two elements.
if you subtract arbitrary pointers, then the result means the memory offset between the two pointers.

13. Is NULL always equal to 0(zero)?
then yes, NULL is always equal to 0. That's the whole point of the definition of a null pointer.
If you mean "is stored the same way as an integer zero," the answer is no, not necessarily. That's the most common way to store a null pointer. On some machines, a different representation is used.
that's why the null pointer is introduced in c++11.

14. Can you add pointers together? Why would you?
no. the result is meaningless.

15.When would you use a pointer to a function?
Pointers to functions are interesting when you pass them to other functions. A function that takes function pointers says, in effect, "Part of what I do can be customized. Give me a pointer to a function, and I'll call it when that part of the job needs to be done. That function can do its part for me." This is known as a "callback." 

16.Can math operations be performed on a void pointer?
No. Pointer addition and subtraction are based on advancing the pointer by a number of elements. But for a void type, you don't know the element size.

17 .How do you print an address?
printf( "%P\n", (void*) buffer );

18. const int * p1 and int * const?
const int means you can modify the pointer but you cann't modify the value;
int const means you cann't modify the value but you can modify the pointer;

18. 4 cast
const_cast : can be used to modify the const attribute of a pointer or variable
reinterpret_cast : Converts between types by reinterpreting the underlying bit pattern of a type to another type.
dynamic_cast : Safely converts pointers and references along the inheritance hierarchy.
static_cast : Converts between types using a combination of implicit and user-defined conversions. 

19. can you call delete this?
delete this is legal and does what you would expect: it calls your class's destructor and free the underlying memory. After delete this returns, your this pointer value does not change, so it is now a dangling pointer that should not be dereferenced. That includes implicit dereferencing using the class's member variables.
It is usually found in reference-counted classes that, when the ref-count is decremented to 0, the DecrementRefCount()/Release()/whatever member function calls delete this.

19. What is the difference between an inspector and a mutator?
- The get() functions are usually refered to as inspectors as that just retrieve the data values from the source. However, mutators that can be refered to as set() finctions change the values of the data source.

20.
What is pointer to member?
- Not to a specific instance of that member in an object. This type of pointer is called a pointer to a class member or a pointer-to-member. It is not same as normal C++ pointer. Instead it provides only an offset into an object of the member’s class at which that member can be found. Since member pointers are not true pointers, the . and → can not be applied to them. Instead we must use the special operators .* and →* . They allow access to a member of a class.
- Example :
#include <iostream>
using namespace std;
class MyClass
{
   public:
       int val;
       MyClass(int i)
       {
          val = i;
       }
       int double_val()
       {
          return val + val;
       }
};
int main()
{
   int MyClass::*data;   //data member pointer
   int(MyClass::*func)();   //function member pointer
   MyClass obj1(1), obj2(2);   //create objects
   data =&MyClass::val;   //get offset of data val
   func=&MyClass::double_val;   //get offset of function double_val()

   cout << “The values are:”;
   cout << ob1.*data << “ “ << ob2.*data << “\n”;
   cout << “Here they are doubled:”;
   cout << (ob1.*func)() << “ “ << (ob2.*func)() << “\n”;

   return 0;
}

21.Why a[5] == 5[a]?
a[b] means *(a+b) by C standard. a is base address, b is an offset starting from a. a[b] is the value in the address of a+b.
Thus a+5 and 5+a is the same memory address. Their value *(a+5) and *(5+a) is the same. So a[5] == 5[a]

22. C pointer to array/array of pointers disambiguation
What is the difference between the following declarations:
int* arr1[8];
int (*arr2)[8];
int *(arr3[8]);
By C precedence table, array [], function return () have higher precedence over pointer *.
For int* arr1[8]
arr1 first and foremost is an array no matter what type the element is. After applying pointer *, we know arr1 is an array of int pointers.
For int (*arr2)[8]
By bracket overriding rule, pointer * has higher precedence over array [] in this case. Then arr2 is first and foremost a pointer no matter what it is pointing to. After applying array [], we know arr2 is a pointer to an array of int.
For int *(arr3[8])
Bracket in this case does not change any default precedence, so it is the same as int* arr1[8]

23.
What is virtual destructors? Why they are used?
Virtual destructors are used for the same purpose as virtual functions. When you remove an object of subclass, which is referenced by a parent class pointer, only destructor of base class will get executed. But if the destructor is defined using virtual keyword, both the destructors [ of parent and sub class ] will get invoked.

24.
 What you mean by early binding and late binding? How it is related to dynamic binding?
Binding is the process of linking actual address of functions or identifiers to their reference.
    During compilation : This is called early binding
    At runtime : This is called late binding.

25.
What are the difference between reference variables and pointers in C++?
Pointers Reference Variables
Pointers can be assigned to NULL References cannot be assigned NULL. It should always be associated with actual memory, not NULL.
Pointers can be (re)pointed to any object, at any time, any number of times during the execution. Reference variables should be initialized with an object when they are created and they cannot be reinitialized to refer to another object

26.
What is difference between shallow copy and deep copy? Which is default?
When you do a shallow copy, all the fields of the source object is copied to target object as it is. That means, if there is a pointer in the source object, shallow copy will copy the same pointer to target object. So you will have two objects pointing to same memory location which is not what you usually want.
In case of deep copy, instead of copying the pointer, the target will create a new object. In this case if you modify the target object, it will not affect the source. By default copy constructors and assignment operators do shallow copy.

27.   mutable 
can be modified even in const object

28.  What are the basics concepts of OOP?
Classes and Objects
Encapsulation
Data abstraction
Inheritance

29.
What are VTABLE and VPTR?
vtable is a table of virtual functions in the class.
vptr is a pointer to vtable.

30.
What is the difference between macro and inline()?
compiler performs strict type check to inline functions rather than macro.
inline and macro will expand at compilation time.

31.
Q:
 Is it possible to have Virtual Constructor? If yes, how? If not, Why not possible?  
A:
 There is nothing like Virtual Constructor. The Constructor can’t be virtual as the constructor  
      is a code which is responsible for creating an instance of a class and it can’t be delegated to   
     any other object by virtual keyword means. 

32.
What is the difference between function overloading and operator overloading?
function overloading: different parameter same return value;
operator overloading: different parameter different return value;

33.What is polymorphism? Explain with an example? 
Polymorphism is the ability of an object (or reference) to be replaced or become many different forms of object. Example: function overloading, virtual functions.

34. What is operator overloading?what r the advantages of operator overloading?
Operator overloading can be overloaded to act on a User-defined operand(Objects).

35. Static Polymorphism and dynamic polymorphism
Static polymorphism is considered more efficient, and dynamic polymorphism more flexible.
Static polymorphism bound function calls at compile time. dynamic polymorphism bound functions calls during run-time. so it need to search the functions during run-time. On the other hand, no run-time search is required for Static polymorphism.
Static Polymorphism may increase program size rapidly, because just copy and paster source code.

36.
Explain how to initialize a const member data.
Use constructor initializer list.

37. When do I need anonymous class in C++?
The feature is there because struct and class are the same thing - anything you can do with one, you can do with the other. It serves exactly the same purpose as an anonymous struct in C; when you want to group some stuff together and declare one or more instances of it, but don't need to refer to that type by name.
It's less commonly used in C++, partly because C++ designs tend to be more type-oriented, and partly because you can't declare constructors or destructors for anonymous classes.

38.
Define upcasting.
Storing the address of the derived class object in the base class pointer.

39.
What is the type of “this” pointer?
It is a constant pointer.
? It will get created if a non-static member function of the class is called up.

40.How we can differentiate between a pre and post increment operators during overloading?
The postfix version of the increment operator takes a dummy int parameter in order to disambiguate:
// prefix
CSample& operator++()
{
  // implement increment logic on this instance, return reference to it.
  return *this;
}
// postfix
CSample operator++(int)
{
  CSample tmp(*this);
  operator++(); // prefix-increment this instance
  return tmp;   // return value before increment
}

41.
Do we have to use initialization list in spite of the assignment in constructors?
We have to use initialization list for initializing const data member.

42.
What is dangling pointer?
? Pointer that does not point to a proper or valid object of the correct type is called Dangling pointer.

43.
What are the storage qualifiers?
Const Volatile  Mutable 

44. What are the implicit member functions of class?
The implicit member functions are
? default ctor
It is mainly used for initializing.
? copy ctor
It is used for creating a new object as a copy of the existing one.
? assignment operator
It is the operator used for assigning values to the variables.
? default destructor
It acts just like the inverse of constructor for de-initializing variables.
? address operator
It connects an operand to its pointer variable.

45. What is Stack unwinding?
When an exception is thrown and control passes from a try block to a handler, the C++ run time calls destructors for all automatic objects constructed since the beginning of the try block. This process is called stack unwinding. The automatic objects are destroyed in reverse order of their construction.

46. How can you link a C++ program to C functions?
? First by using the extern "C" linkage specification 

47. Why should I avoid multiple inheritance in C++?
it's difficult to maintain, it's better to inheritance multiple interfaces.

48. Q: Can you think of a situation where your program would crash without reaching the
breakpoint which you set at the beginning of main()?
A: It is possible that initialization of global will invoke some function. 

49.
Why do C++ compilers need name mangling?
A: Name mangling is the rule according to which C++ changes function's name into function
signature before passing that function to a linker. This is how the linker differentiates between
different functions with the same name.

50.
Q: How the compiler arranges the various sections in the executable image?
A: The executable had following sections:
(a) Data Section (uninitialized data variable section, initialized data variable section )
(b) Code Section
(c) Remember that all static variables are allocated in the initialized variable section.

51.
Q: Can inline functions have a recursion?
A: No.

52.
Q: What are some advantages/disadvantages of using friend functions?
A: Sometimes class has some data members or functions which shouldn't be public, but they should be exposed to some class in special case, in this sinerio friend should be used.
If they're not used properly, they violate encapsulation.

53.
Q: Can a copy constructor accept an object of the same class as parameter, instead of reference
of the object?
A: No.

54.
Q: How can I handle a constructor that fails?
A: throw an exception. Constructors don't have a return type, so it's not possible to use return
codes. The best way to signal constructor failure is therefore to throw an exception.

55.
Q: How can I handle a destructor that fails?
A: Write a message to a log-_le.

56.
Q: What is "placement new" and why would I use it?
A: There are many uses of placement new. The simplest use is to place an object at a particular
location in memory. This is done by supplying the place as a pointer parameter to the new part of
a new expression:
#include // Must #include this to use "placement new"
#include "Fred.h" // Declaration of class Fred
void someCode()
{
char memory[sizeof(Fred)]; // Line #1
void* place = memory; // Line #2
Fred* f = new(place) Fred(); // Line #3 (see "DANGER" below)
// The pointers f and place will be equal
...
}
A: No. You never need to explicitly call a destructor (except with placement new).

57.
Q: Should my constructors use "initialization lists" or "assignment"?
A: Initialization lists. In fact, constructors should initialize as a rule all member objects in the
initialization list. more efficient. const member has to be initialized with initialize list.

58.Q: Should you use the this pointer in the constructor?
yes

59. Q: When should you use multiple inheritance?
A:There are three acceptable answers:- "Never,""Rarely," and "When the problem domain
cannot be accurately modeled any other way." Consider an Asset class, Building class, Vehicle
class, and CompanyCar class. All company cars are vehicles. Some company cars are assets
because the organizations own them. Others might be leased. Not all assets are vehicles. Money
accounts are assets. Real estate holdings are assets. Some real estate holdings are buildings. Not
all buildings are assets. Ad infinitum. When you diagram these relationships, it becomes
apparent that multiple inheritance is a likely and intuitive way to model this common problem
domain. The applicant should understand, however, that multiple inheritance, like a chainsaw, is
a useful tool that has its perils, needs respect, and is best avoided except when nothing else will
do.

60. Q: Explain the ISA and HASA class relationships. How would you implement each in a class
design?
A: A specialized class "is" a specialization of another class and, therefore, has the ISA
relationship with the other class. This relationship is best implemented by embedding an object
of the Salary class in the Employee class.

21. how to implement auto in c++?

2. exception implementation

3. move and right reference

4. function call stack frame

3. shared pointer implementation

4. little endian and big endian

1. Count from 1 to 1000 without using loops

#include <stdio.h>
#include <stdlib.h>
 
void main(int j) {
  printf("%d\n", j);
  (&main + (&exit - &main)*(j/1000))(j+1);
}

The only other method to count 1 to 1000 is using recursion. According to C language, j has ‘1’as its value at the beginning. When 1 <= j < 1000, &main + (&exit - &main)*(j/1000) always evaluated to &main, which is the memory address of main. (&main)(j+1) is the next iteration we want to get, which would print ‘2’ on the screen, etc. The stop condition of this recursion is that When j hits 1000, &main + (&exit - &main)*(j/1000) evaluates to &exit, which will elegantly exit this process, and has the error code 1001 returned to the operating system.

  评论这张
 
阅读(14)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017