1. What and why is explicit constructor and explicit copy constructor?
2. What the difference between Struct and Class?
3. What is vitrual function and why we need vtable?
1.
Explicit constructor and copy constructor is used to preventing implicit type cast.
An explicit constructor can not take part in implicit conversions. It can only be used to explicit construct an object
Consider the Class below:
class A
{
public:
A();
A(int i);
A(A& a);
int i;
virtual ~A();
};
The following program will success to compile :
A a = 10;
or
A a;
a = 10;
because A has a constructor that accept a Int as a arguments
Those codes above are equal to
A tmp(10); //constructor
a(tmp); //copy constructor
or
A tmp(10) ; //constructor
a = tmp; // operator =
Note: explicit on a constructor with mutiple arguments has no
effect, unless all but one of the arguments has a default value !
2: differences between struct and class?
3 difference between struct and class
1)members in struct are by default public while members in class are by default private.
2)inhert from a struct is by default public , inhert from a class is by default private.
For example
struct A
{
};
struct B : (public)A
{
} ;
class A
{
};
class B: (private)A
{
};
3)class can be used as typename in template while struct can not
template(class T) //right
template(struct T) //wrong
3: What is virtual function and why we need vtable?
1) a virtual function is a function member of a class decleared with a virtual keyword
2) it usually has a different functionality in the derived class
3) A function is resolved at run-time
The main difference between a non_virtual function and a virtual
function is, the non_virtual function is resolved at compile time.
This mechanism is called static_binding. As the virtual function is
resolved at run time, This mechanism is know as dynamic_binding
v_table is kind of lookup table.It contains pointers to the virtual
functions provided by a class, and each object of the class contains
a pointer to its v_table(or vtables, in some multiple-inheritance
situations)
A v_table is created at compile time, so whether a object is
referenced by any pointers or reference, when a virtual fall happens,
the v_table can help the object find the exact function address.