Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a compiler differentiate between static data members having same name in different classes in C++?

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.

like image 990
San Avatar asked Oct 04 '10 17:10

San


People also ask

What is a static data member how they are used in static functions explain with suitable illustrations?

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.

Why static members are defined outside the class?

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.

What are static members of a class when and how are they useful?

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?

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.


2 Answers

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
like image 121
Johannes Schaub - litb Avatar answered Sep 21 '22 16:09

Johannes Schaub - litb


It's implementation-defined, so there's no one way it has to be done.

Name mangling is commonly used though.

like image 39
Jon Hanna Avatar answered Sep 19 '22 16:09

Jon Hanna