I had a C++ interview recently where I was asked, how does the compiler differentiate static data members having the same name in two different classes?
Since all static data variables are stored in the data segment, there has to be a way by which the compiler keeps track of which static data belongs to which class especially when they have the same name.
Edit: I answered name mangling, but he refused saying name mangling is used only among the members of the same class.
Static data members are class members that are declared using static keywords. A static member has certain special characteristics. These are: Only one copy of that member is created for the entire class and is shared by all the objects of that class, no matter how many objects are created.
Because static member variables are not part of the individual class objects (they are treated similarly to global variables, and get initialized when the program starts), you must explicitly define the static member outside of the class, in the global scope.
When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class. All static data is initialized to zero when the first object is created, if no other initialization is present.
Which is the correct syntax for declaring static data member? Explanation: The syntax must firstly be mentioned with the keyword static. Then the data type of the member followed by the member name should be given. This is general form of declaring static data members.
The names are mangled with their class name in them. An example with the clang compiler
class A {
static int i;
};
int A::i = 0;
Output
$ clang++ -cc1 -emit-llvm main1.cpp -o -
; ModuleID = 'main1.cpp'
target datalayout = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:32:64-f32:32:32-f64:32:64-v64:64:64-v128:128:128-a0:0:64-f80:32:32-n8:16:32"
target triple = "i386-pc-linux-gnu"
@_ZN1A1iE = global i32 0, align 4
Where _ZN1A1iE
is
$ c++filt _ZN1A1iE
A::i
It's implementation-defined, so there's no one way it has to be done.
Name mangling is commonly used though.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With