Microsoft KB Archive/152211

= FIX: Constructor Gets Called Multiple Times on the Same Object =

Article ID: 152211

Article Last Modified on 7/5/2005

-

APPLIES TO


 * Microsoft Visual C++ 4.1 Subscription
 * Microsoft Visual C++ 4.2 Enterprise Edition
 * Microsoft Visual C++ 5.0 Enterprise Edition
 * Microsoft Visual C++ 6.0 Enterprise Edition
 * Microsoft Visual C++ 4.2 Professional Edition
 * Microsoft Visual C++ 5.0 Professional Edition
 * Microsoft Visual C++ 6.0 Professional Edition
 * Microsoft Visual C++ 6.0 Standard Edition

-



This article was previously published under Q152211



SYMPTOMS
The constructor gets called more than once on the same global object.



CAUSE
This error occurs when a file has both a global object and a function that references the global object as extern. In this case, the compiler incorrectly generates code that calls the constructor on the "extern myClass object;" statement.



RESOLUTION
Remove the line that contains extern reference to the global. You can safely remove this line since the global is in file scope.

-or-

Create two separate files, one that contains the global object, and one that contains the function that references the global object as extern.



STATUS
Microsoft has confirmed this to be a bug in the Microsoft products listed at the beginning of this article.

This problem was corrected in Microsoft Visual C++ .NET.



Sample Code
// This sample demonstrates the problem of the constructor getting // called twice. /* Compile options needed: cl test.cpp // TEST.CPP // ======== class myClass { public: myClass {printf("myClass Constructor called\n");}; void test {printf("test called\n");}; } object;
 * 1) include "stdio.h"

void main { // Remove the next line for the first workaround: extern myClass object; object.test; }

// sample output: (without extern line removed) myClass Constructor called myClass Constructor called test called

// This sample demonstrates the workaround that causes the program // to only call the constructor once. /* Compile options needed: cl Test2A.cpp Test2B.cpp // Test2.h // ======== class myClass { public: myClass {printf("myClass Constructor called\n");}; void test {printf("test called\n");}; }; // Test2A.cpp // ========== myClass object;
 * 1) include "stdio.h"
 * 1) include "Test2.h"

// Test2B.cpp // ========== void main { extern myClass object; object.test; }
 * 1) include "Test2.h"

// sample output: myClass Constructor called test called

Additional query words: 10.10 10.20

Keywords: kbbug kbfix kbnoupdate kbcpponly kbcompiler KB152211

-

[mailto:TECHNET@MICROSOFT.COM Send feedback to Microsoft]

© Microsoft Corporation. All rights reserved.