标 题: C++ interview question
发信站: BBS 未名空间站 (Wed Oct 15 20:28:51 2008)
Comments are welcomed, thanks
1) What is difference of overridden and overload? ( I mentioned for
overload, the scope is usually the same, e.g., at same class scope, but the
interviewer said it could be different, e.g., in base class and derived
class, but that is hiding, not overload, isn’t it?)
2) How to achieve polymorphism? (I mentioned virtual function, he asked
more, then I mentioned RTTI, dynamic_cast then use if-else logic to check)
3) How to prohibit inheritance? (put cotor in private part of class?) What is the prohibition, e.g., compiler complain or running time error?
http://www.devx.com/cplus/10MinuteSolution/31881/0/page/3
4) why use dynamic_cast, it required at least virtual function defined?
dynamic_cast
reinterpret_cast
static_cast
const_cast
dynamic_cast can be used only with pointers and references to objects. Its purpose is to ensure that the result of the type conversion is a valid complete object of the requested class.
When a class is polymorphic, dynamic_cast performs a special checking during runtime to ensure that the expression yields a valid complete object of the requested class. dynamic_cast requires the Run-Time Type Information (RTTI) to keep track of dynamic types. Some compilers support this feature as an option which is disabled by default. This must be enabled for runtime type checking using dynamic_cast to work properly.
static_cast can perform conversions between pointers to related classes, not only from the derived class to its base, but also from a base class to its derived. This ensures that at least the classes are compatible if the proper object is converted, but no safety check is performed during runtime to check if the object being converted is in fact a full object of the destination type. Therefore, it is up to the programmer to ensure that the conversion is safe. On the other side, the overhead of the type-safety checks of dynamic_cast is avoided.
reinterpret_cast converts any pointer type to any other pointer type, even of unrelated classes. The operation result is a simple binary copy of the value from one pointer to the other. All pointer conversions are allowed: neither the content pointed nor the pointer type itself is checked.
const_cast This type of casting manipulates the constness of an object, either to be set or to be removed.