Hidden overheads with empty Constructor/Destructor

Consider the following C++ code: 

        class A {
                int x, y, z;
        public:
                A();
        };

        class B {
                A a;
        public:
                B() {}
        };

        A::A() {x = 0; y = 0; z = 0;}

Class A has a constructor A::A(), used to initialize three of the class’s data members. Class B has a constructor declared inline (defined in the body of the class declaration). The constructor is empty.

Suppose that we use a lot of B class objects in a program. Each object must be constructed, but we know that the constructor function body is empty. So will there be a performance issue?

The answer is possibly “yes”, because the constructor body really is NOT empty, but contains a call to A::A() to construct the A object that is part of the B class. Direct constructor calls are not used in C++, but conceptually we could think of B’s constructor as containing this code: 

        B::B() {a.A::A();}      // construct “a” object in B class

There’s nothing wrong about doing things; it falls directly out of the language definition. But in complex cases, such as ones involving multiple levels of inheritance, a seemingly empty constructor or destructor can in fact contain a large amount of processing.

1 Response to “Hidden overheads with empty Constructor/Destructor”


  1. 1 div June 20, 2008 at 12:32 pm

    Thanks for the article. But the construction of A object happens even in the absence of the empty constructor.

Leave a Reply




 

August 2007
S M T W T F S
« Jul   Sep »
 1234
567891011
12131415161718
19202122232425
262728293031  

Categories

Blog Stats

  • 29,660 hits

Last 100 Visitors

Map IP Address

Map IP Address