Sunday, September 09, 2007

Inside the c++ object model (2)

Two common misunderstandings for default constructor:
  1. A default constructor is created for every class that does not define one.
  2. The compiler-created default constructor provides explicit default initializers for each data member declared within the class
In 4 cases, the compiler needs to create a default constructor for classes that declare no constructor at all.
  1. member class object with default constructor
  2. base class with default constructors
  3. class with the virtual function
  4. virtual base class mechanism for each object
If it is not these 4 cases, and declare no constructor at all, the default constructors are not created.
case 1:
class Foo { public: Foo(), Foo(int) ...};
class Bar { public: Foo foo; char *str;};
void foo_bar(){
Bar bar; // Bar::foo must be initialized here
if ( str ) {} ...
}

The created default constructor contains the code necessary to invoke the class Foo default constructor on the member object Bar::foo, but it doesn't generate any code to initialize Bar::str. If there are multiple class member objects, it inserts code within each constructor, invoking the associated default constructors for each member in the order of member declaration.

case 2: the created default constructor of the derived class invokes the default constructor of each of its immediate base classes in the order of their declaration.

No comments:

Post a Comment