Predict the output of following C++ program:
B's Constructor Called
The above program calls only B’s constructor, it doesn’t call A’s constructor. The reason for this is simple, static members are only declared in class declaration, not defined. They must be explicitly defined outside the class using scope resolution operator.
If we try to access static member ‘a’ without explicit definition of it, we will get compilation error. For example, following program fails in compilation.
Compiler Error: undefined reference to `B::a'
If we add definition of a, the program will works fine and will call A’s constructor. See the following program.
A's constructor called B's constructor called B's constructor called B's constructor called
Note that the above program calls B’s constructor 3 times for 3 objects (b1, b2 and b3), but calls A’s constructor only once. The reason is, static members are shared among all objects. That is why they are also known as class members or class fields. Also, static members can be accessed without any object, see the below program where static member ‘a’ is accessed without any object.
A's constructor called
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Memory Allocation in Static Data Members in C++
- Initialization of data members
- Can we access private data members of a class without using a member or a friend function?
- Difference between static and non-static method in Java
- Difference between static and non-static variables in Java
- Internal static variable vs. External static variable with Examples in C
- Understanding storage of static methods and static variables in Java
- Why non-static variable cannot be referenced from a static method in Java
- Understanding "static" in "public static void main" in Java
- Class Loading and Static Blocks Execution Using Static Modifier in Java
- Are array members deeply copied?
- Flexible Array Members in a structure in C
- Different ways to Initialize all members of an array to the same value in C
- C++ Program to swap two members using Friend Function
- Static functions in C
- How are variables scoped in C - Static or Dynamic?
- Can static functions be virtual in C++?
- What are the default values of static variables in C?
- Templates and Static variables in C++
- Comparison of static keyword in C++ and Java