Sunday, January 11, 2009

C++ FAQ v0.01 (Collection)

1. What is virtual destructor?
For the codes:
#include
class Base
{
public:
...
~Base(){ cout<<"Base Destructor"<};
class Derived: public Base
{
//Doing a lot of jobs by extending the functionality
public:
...
~Derived(){ cout<<"Derived Destructor"<> };
void main()
{
Base *p = new Derived();
delete p;
}

You will find:
only the "Base Destructor" is printed which means that only
the based destructor is called.

If we define VIRTUAL DESTRUCTOR in based class as:
virtual ~Base(){ cout<<"Base Destructor"<you will find that
Derived and based destructors are called in order.

2. How to define pure virtual function?
It is used in abstract base class to define pure virtual function as:
virtual int pA() const=0;

3. Can we have virtual constructor?
It is fancy, but in C++, the answer is no.

4. What is a polymorphism? How to implement it?
Polymorphism is the ability to use an operator or function in different ways. A single function usage or an operator functioning in many ways can be called polymorphism. Polymorphism refers to codes, operations or objects that behave differently in different contexts. In C++, one uses
virtual function to implement polymorphism. However, this is not the only methods. Operators overloading and Function name overloading are two other ways to achieve this kind of behavior.

BTW: There have other concepts: 1)run-time pm by inheritance and virtual function 2) compile-time polymorphism(templates) 3) Ad-hoc pm 4) parametric pm

5. What is the encapsulation?
encapsulation is the process of combining data and functions into a single unit called class.
Through the encapsulation, the programmer can not directly access to data(Data hiding) and therefore preventing unauthorized access to data.

6. Which constructor gets called when I create an array of objects?
If we directly call like:
ClassA *cA=new ClassA[10];
and if in the class, we do not define/have the default constructor, it will be syntax error.
To pass the parameters, we have to use STL as:
vector cA(10,ClassA(parameters)));
or use
ClassA cA[10]={ClassA(parameters), ...,ClassA(parameters)};
It is stupid but one has to do it.

7. What is the difference between copy constructor and assignment?
The members and base classes of a struct are public by default, while in class, they default to private. Note: you should make your base classes explicitly public, private, or protected, rather than relying on the defaults.

struct and class are otherwise functionally equivalent.

8. Is the default constructor always like ClassA ();
No! If we have have one which can take arguments, provided they are given default values
like ClassA(int a=1,int b=2); But usually, people always think no argument means default.


9. What is Named Constructor Idiom?
It is a technique that provides more intuitive and/or safer construction operations for users of your class. With the Named Constructor Idiom, you declare all the class's constructors in the private or protected sections, and you provide public static methods that return an object. These static methods are the so-called "Named Constructors." In general there is one such static method for each different way to construct an object. For example:


#include // To get sin() and cos()

class Point {
public:
static Point rectangular(float x, float y); // Rectangular coord's
static Point polar(float radius, float angle); // Polar coordinates
// These static methods are the so-called "named constructors"
...
private:
Point(float x, float y); // Rectangular coordinates
float x_, y_;
};

inline Point::Point(float x, float y)
: x_(x), y_(y) { }

inline Point Point::rectangular(float x, float y)
{ return Point(x, y); }

inline Point Point::polar(float radius, float angle)
{ return Point(radius*cos(angle), radius*sin(angle)); }

Now the users of Point have a clear and unambiguous syntax for creating Points in either coordinate system:

int main()
{
Point p1 = Point::rectangular(5.7, 1.2); // Obviously rectangular
Point p2 = Point::polar(5.7, 1.2); // Obviously polar
...
}

10 What are the interface and abstract class?

An abstract class contains at least one pure virtual function.
An interface class [usually] doesn't have any data members.
C++ has no notion of an "interface" class; however applying the Java
terminology to C++, an interface class would basically be an abstract
class that is composed entirely of pure virtual functions.

11. What are the struct and union?

A structure is a collection of items of different types; and each data item will have its own memory location. Where as only one item within the union can be used at any time, because the memory allocated for each item inside the union is in a shared memory location i.e., only one memory location will be shared by the data items of union.

The difference between structure and union are:
a. union allocates the memory equal to the maximum memory required by the member of the union but structure allocates the memory equal to the total memory required by the members.
b. In union, one block is used by all the member of the union but in case of structure, each member have their own memory space

12. What is the "explicit" keyword in constructor?

n C++, a constructor with only one required parameter is considered an implicit conversion function. It converts the parameter type to the class type. Whether this is a good thing or not depends on the semantics of the constructor.

The explicit function specifier controls unwanted implicit type conversions. It can only be used in declarations of constructors within a class declaration. For example, except for the default constructor, the constructors in the following class are converting constructors.

class A
{ public:
A();
A(int);
A(const char*, int = 0);
};
The following declarations are legal.

A c = 1;
A d = "Venditti";
The first declaration is equivalent to A c = A(1).

If you declare the constructor of the class with the explicit keyword, the previous declarations would be illegal.

For example, if you declare the class as:

class A
{ public:
explicit A();
explicit A(int);
explicit A(const char*, int = 0);
};
You can only assign values that match the values of the class type.

For example, the following statements will be legal:

A a1;
A a2 = A(1);
A a3(1);
A a4 = A("Venditti");
A* p = new A(1);
A a5 = (A)1;
A a6 = static_cast(1);

In summary, if your single-parameter constructor converts the parameter into an object of your class, you probably don't want to use the explicit keyword. But if you have a constructor that simply happens to take a single parameter, you should declare it as explicit to prevent the compiler from surprising you with unexpected conversions.

13. What is virtual inheritance?
virtual inheritance is a kind of inheritance that solves some of the problems caused by multiple inheritance (particularly the "diamond problem") by clarifying ambiguity over which ancestor class members to use. It is used when inheritance is representing restrictions of a set rather than composition of parts. A multiply-inherited base class is denoted as virtual with the virtual keyword.
In a class structure in which a particular class appears more than once in a class's inheritance hierarchy, one usually use virtual inheritance to make the base class which
are duplicated to unique.
Generally, virtual base classes are most suitable when the classes that derive from the virtual base, and especially the virtual base itself, are pure abstract classes.

14. What is function object?
A function object, also called a functor, functional or functionoid, is a computer programming construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax.
In C, it just is a function pointer.
/* Callback function */
int compare_function(int A, int B) {
return (A < B);
}
...
/* Declaration of C sorting function */
void sort_ints(int* begin_items, int num_items, int (*cmpfunc)(int, int) );
...
int main() {
int items[] = {4, 3, 1, 2};
sort_ints(items, sizeof(items)/sizeof(int), compare_function);
}

In C++ a functor may be used instead of an ordinary function by defining a class which overloads the function call operator by defining an operator() member function.
class compare_class {
public:
bool operator()(int A, int B) {
return (A < B);
}
};
...
// Declaration of C++ sorting function.
template
void sort_ints(int* begin_items, int num_items, ComparisonFunctor c);
...
int main() {
int items[] = {4, 3, 1, 2};
compare_class functor;
sort_ints(items, sizeof(items)/sizeof(int), functor);
}

In STL, it is used extensivelty.

15. What is a function adaptor?
A function adaptor is an instance of a class that adapts a namespace-scope or member function so that the function can be used as a function object.

An adaptor itself is a component that modifies the interface of another component, thus letting you use that component in a new context. STL uses several types of adaptors:
A sequence adaptor is a container that's built on another container and that modifies its interface. For example, the container stack is usually implemented as a deque, whose non-stack operations are hidden. In addition, stack uses the operations back(), push_back(), and pop_back() of a deque to implement the operations top(), push(), and pop(), respectively.

The interface of an iterator can be altered by an iterator adaptor. The member functions rend() and rbegin() return reverse iterators, which are iterators that have the meanings of operators ++ and -- exchanged. Using a reverse iterator is more convenient in some computations.

Function adaptors modify the interface of a function or a function object. Earlier you saw the use of greater as a function adaptor for changing the computation of sort().

Negators are used to reverse the result of certain Boolean operations.

Binders convert a binary function object into a unary function object by binding an argument to a specific value.

http://blog.chinaunix.net/u2/75321/showart_1159749.html

16. What is memory leak? And how to detect it and solve it?

The failure to properly deallocate memory that was previously allocated.

To detect it in CRT
You can dump memory leak information by including the following statement in your program:


Code:
#include

#define _CRTDBG_MAP_ALLOC
#include

int main()
{
int* array = new int[10];
_CrtDumpMemoryLeaks();
return 0;
}

TO solve it, Make sure that:
you use correctly 'new'/'delete' and 'new[]'/'delete[]' (also 'malloc'/'free')
pointers don't go out of scope before memory is released
if you allocate memory in a loop, you release it in each iteration

17. Where are the variables stored at?
The memory a program uses is typically divided into four different areas:

The code area, where the compiled program sits in memory.
The globals area, where global variables are stored . It calls as static storage area.
The heap, where dynamically allocated variables are allocated from.
The stack, where parameters and local variables are allocated from.


The heap (also known as the “free store”) is a large pool of memory used for dynamic allocation. In C++, when you use the new operator to allocate memory, this memory is assigned from the heap.

The heap has advantages and disadvantages:
1) Allocated memory stays allocated until it is specifically deallocated (beware memory leaks).
2) Dynamically allocated memory must be accessed through a pointer.
3) Because the heap is a big pool of memory, large arrays, structures, or classes should be allocated here.

The stack
parameters and local variables essentially belong to a function, they are stored
in stack

The stack has advantages and disadvantages:

Memory allocated on the stack stays in scope as long as it is on the stack. It is destroyed when it is popped off the stack.
All memory allocated on the stack is known at compile time. Consequently, this memory can be accessed directly through a variable.
Because the stack is relatively small, it is generally not a good idea to do anything that eats up lots of stack space. This includes allocating large arrays, structures, and classes, as well as heavy recursion.

Notice If local variables are references types, this space is used as a reference (aka pointer) to the actual value, which is stored on the heap.
So to summarise:

C and C++ have three types of storage:

1/ Static storage for function-local and internal and external global objects that have storage allocated for the whole of the program duration. Complex static objects requiring dynamic initialisation may not be fully initialised (created) until some later point (if at all) in a programs execution - but once fully created they exist until destroyed during program termination.

2/ Automatic storage on the stack. Such objects apply only to objects defined locally to a function. They exist until the function returns or for a shorter time if they have a smaller scope within the function. Automatic storage is the default storage class for local function objects.

Stacks are allocated on a per unit of execution basis.

3/ Dynamic storage on the free store or heap is managed at runtime (i.e. dynamically) via explicit calls or operators - e.g. new and delete. Objects allocated from the free store exist until explicitly released (freed, deleted, deallocated, etc...).

In addition:

4/ The terms static and dynamic when used in the context of C++ programs often mean "at compile / link time" (static) and "at run time" (dynamic).

5/ A function or object (variable) definition reserves storage for that entity. A declaration merely states that such an entity exists. Such entities can only be _defined_ once in a program. However they can be declared to exist as many times as required. A function declaration is sometimes called a function prototype (from C). Most definitions in C and C++ are also declarations. Only global objects with external linkage can have declarations in C and C++, all other such statements are definitions (and declarations).


18. Multiplex I/O ( Network I/O)
http://www.onlamp.com/pub/a/python/2004/02/12/advanced_nio.html?page=1
a. Synchronous I/O is the simplest method for your networked application. Basic synchronous I/O provides no concurrency at all; the program stops at each operation, waiting for it to complete. This technique is sufficient for simple

b. Multitasking is an operating system feature that allows several jobs to be done concurrently. All modern, mainstream operating systems such as Linux, Solaris, Windows, and Mac OS X support multitasking.
Thread-per-Request /Thread Pool

c.Asynchronous I/O
Asynchronous I/O is a technique specifically targeted at handling multiple I/O requests efficiently. In contrast, threads are a general concurrency mechanism that can be used in situations not related to I/O. Most modern operating systems, such as Linux and Windows, support asynchronous I/O.
Asynchronous I/O works very differently from threads. Instead of having an application spawn multiple tasks (that can then be used to perform I/O), the operating system performs the I/O on the application's behalf. This makes it possible for just one thread to handle multiple I/O operations concurrently. While the application continues to run, the operating system takes care of the I/O in the background.


18. Pointer-to-Pointer and Reference-to-Pointer
This is how you call the function with a ptr-to-ptr parameter:

//function prototype
void func(int** ppInt);

int main()
{
int nvar=2;
int* pvar=&nvar;
func(&pvar);
....
return 0;
}
Now, let us look at how you called the function with the ref-to-ptr parameter:

//function prototype
void func(int*& rpInt);

int main()
{
int nvar=2;
int* pvar=&nvar;
func(pvar);
....
return 0;
}

18. Why use pointer to pointer?

To generate multidimensinal array.

grid = new ClassA*[sizeD1];

for (int i=0; i grid[i] = new ClassA[sizeD2);

Notice ClassA must have a default constructor,
otherwise we have to use STL vector (like
vector> grid(sizeD2, vector(sizeD1, ClassA(...))); or assign them explicitly See: http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12

19 What is function pointer , point-to-function and point-to-memeber?
There have two types of function pointers:
On the one hand there are pointers to ordinary C functions or to static C++ member functions. On the other hand there are pointers to non-static C++ member functions. The basic difference is that all pointers to non-static member functions need a hidden argument: The this-pointer to an instance of the class. Always keep in mind: These two types of function pointers are incompatible with each other.
it is an ordinary function or a non-static member function of some class:

Its type is "int (*)(char,float)" if an ordinary function
Its type is "int (Fred::*)(char,float)" if a non-static member function of class Fred

Note: if it's a static member function of class Fred, its type is the same as if it were an ordinary function: "int (*)(char,float)".

20. What is the smart pointer and this pointer?
Smart pointers are C++ objects that simulate simple pointers by implementing operator-> and the unary operator*.




**************************************************************************
Some answers might be directly collected from the web by using google search.
I will not enclose the link as usually I used different resource to answer those questions.
But if someone thinks the copyright is violated, please contact me and I will
rewrite the answer...