[Rock-dev] C++ Style: Shadowing "Class Member Variables" with "Constructor Call Variables"

Martin Zenzes martin.zenzes at dfki.de
Thu Dec 11 14:24:18 CET 2014


Hi,

as came up on github here [1] and here [2], I think there is the some 
lingering problem in our code base.

Suppose there is a member-variable "a" of the "class TestClass" and a 
variable in the arguments of the Constructor with the same name, used 
for initialization of the member-variable in the initializer-list, no 
problem. But assigning to the variable named "a" in the body of the 
constructor will change the one from the constructor, not the 
member-variable.

So when writing something like this:

     class TestClass {
       public:
         std::string a;
         TestClass(std::string a):a(a){ a = "3"; }
     };

Note: The code is not broken as such, just unnecessarily dangerous. The 
member "a" is not 3 after initialization, as some uncritical human 
observer might hastily assume. Changing it to something like

     class TestClass {
       public:
         std::string a;
         TestClass(std::string _a):a(_a){ a = "3"; }
     };

will remove the trap. I created an ideone [3] summarizing this, with an 
interesting but more or less unrelated follow-up question related to the 
const-refs on Stack-Overflow [4].

As a side effect, after changing the naming as proposed, paranoid 
compiler-warnings like "-Wshadow" are becoming actually usable, which 
would help to catch the real nasty shadowing-bugs.

Your thoughts?

Greetings
     Martin

[1] 
https://github.com/rock-core/tools-orogen_metadata/pull/1#discussion_r21596070
[2] https://github.com/rock-core/base-types/pull/22#issuecomment-66499129
[3] http://ideone.com/NDI9Gw
[4] 
https://stackoverflow.com/questions/27423364/binding-const-of-temporary-no-compiler-warning

-- 
M.Sc. Martin Zenzes
Space Robotics

Hauptgeschäftsstelle Standort Bremen:
DFKI GmbH
Robotics Innovation Center
Robert-Hooke-Straße 5
28359 Bremen, Germany

Phone: +49 (0) 421 178 45 - 6658
Fax: +49 (0) 421 178 45 - 4150
E-Mail: martin.zenzes at dfki.de

Weitere Informationen: http://www.dfki.de/robotik
-----------------------------------------------------------------------
Deutsches Forschungszentrum fuer Kuenstliche Intelligenz GmbH
Firmensitz: Trippstadter Straße 122, D-67663 Kaiserslautern
Geschaeftsfuehrung: Prof. Dr. Dr. h.c. mult. Wolfgang Wahlster
(Vorsitzender) Dr. Walter Olthoff
Vorsitzender des Aufsichtsrats: Prof. Dr. h.c. Hans A. Aukes
Amtsgericht Kaiserslautern, HRB 2313
Sitz der Gesellschaft: Kaiserslautern (HRB 2313)
USt-Id.Nr.: DE 148646973
Steuernummer: 19/673/0060/3
-----------------------------------------------------------------------



More information about the Rock-dev mailing list