Thursday, 11 April 2013

Question: Why is "this" not a reference?


Question: Why is "this" not a reference?

 Answer: Because "this" was introduced into C++ before references were added.

Question: Why doesn't C++ have an equivalent to realloc()?


Question: Why doesn't C++ have an equivalent to realloc()?

 Answer: If you want to, you can of course use realloc(). However, realloc() is only guaranteed to work on arrays allocated by malloc() (and similar functions) containing objects without user-defined copy constructors. Also, please remember that contrary to naive expectations, realloc() occationally does copy its argument array.
In C++, a better way of dealing with reallocation is to use a standard library container, such as vector, and let it grow naturally.

Question: Why do C++ compilers need name mangling?


Question: Why do C++ compilers need name mangling?

 Answer: 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.

Question: What's the value of i++ + i++?


Question: What's the value of i++ + i++?

Answer: It's undefined. Basically, in C and C++, if you read a variable twice in an expression where you also write it, the result is undefined. Don't do that. Another example is:
v[i] = i++;

Related example:
f(v[i],i++);

Here, the result is undefined because the order of evaluation of function arguments are undefined. Having the order of evaluation undefined is claimed to yield better performing code. Compilers could warn about such examples, which are
typically subtle bugs (or potential subtle bugs). I'm disappointed that after decades, most compilers still don't warn, leaving that job to specialized, separate, and underused tools.

Question: What is Pure Virtual Function? Why and when it is used ?


Question: What is Pure Virtual Function? Why and when it is used ?

Answer: The abstract class whose pure virtual method has to be implemented by all the classes which derive on these. Otherwise it would result in a compilation error.

This construct should be used when one wants to ensure that all the derived classes implement the method defined as pure virtual in base class.