[Exceptional C++ Style] Item 14: Order, Order!

Raj Jammalamadaka cppuser2002 at yahoo.com
Thu Dec 9 19:47:46 EST 2004


Item 14: Order, Order!

1. JG Question

What is wrong with this code and why?

#include <string>
using namespace std;

class A{
public:
	A(const string& s){/*…..*/}
	String f() {return “hello, world”;}
};

class B: public A{
public:
B():A(s=f() ) {}
private:
  string s;
};

int main() {
 B b;
}

Solution:

The problem is in this line

B():A(s = f() ) {}

This line of code tries to use the A base subobject
before it exists. However most compilers will not flag
the abuse of A::f in that the member function f is
being called on an A subobject that hasn’t yet been
constructed. 

The second problem is this line tries to use the s
member object before it exists by calling the member
function operator=  on a string  member subobject that
hasn’t been constructed.

2. Guru Question

When you create a C++ object of class type, in what
order are its various parts initialized?

Solution:
The following set of rules is applied recursively:

1.	First, the most derived class’s constructor calls
the constructor of the virtual base class subobjects.
Virtual base classes are initialized in depth-first,
left-to-right order.
2.	Next, direct base class subobjects are constructed
in the order they are declared in the class
definition.
3.	Next, (nonstatic) member subobjects are constructed
in the order they were declared in the class
definition.
4.	Finally, the body of the constructor is executed.

The main point of this item is to understand the order
in which objects are constructed.

Guideline suggested: Avoid using inheritance.
Except for friendship, inheritance is the strongest
relationship that can be expressed in C++ and should
be used only when it’s necessary.




Thanks,

Raj


		
__________________________________ 
Do you Yahoo!? 
The all-new My Yahoo! - What will yours do?
http://my.yahoo.com 



More information about the Effective-cpp mailing list