C++ static member functions: evaluate two claims about their access and how they are called.
-
AOnly 1 is correct.
-
BOnly 2 is correct.
-
CBoth 1 and 2 are correct.
-
DBoth 1 and 2 are incorrect.
Answer
Correct Answer: Both 1 and 2 are correct.
Explanation
Introduction / Context:Static member functions operate at the class level, not on a particular object instance. They are commonly used to manipulate static data members, implement factories, or provide utility operations closely tied to a class's abstraction, while not requiring an object pointer (this) at the call site. This question asks you to validate two common statements about them: access constraints and call syntax.
Given Data / Assumptions:
- Statement 1: A static member function can access only other static members of its class.
- Statement 2: A static member function can be called using the class name, not just objects.
- We consider standard C++ rules for static members.
Concept / Approach:
Because static member functions do not have an implicit object (no this pointer), they cannot directly access non-static data members or non-static member functions, which require an object context. They can, however, access static data members and call other static member functions. For invocation, the canonical form is ClassName::func(...), although calling through an object is syntactically allowed but unnecessary. Therefore, both statements accurately describe static member functions.
Step-by-Step Solution:
Confirm lack of this pointer → can't access instance members directly. Static functions/data are class-level → accessible. Call via ClassName::func() → valid and idiomatic. Hence, both statements are true.Verification / Alternative check:
Attempt to use a non-static data member inside a static function; the compiler complains about missing object. Access a static counter or call another static function; compilation succeeds. Invoke the function as T::f() and also via an instance; both compile, the former being clearer.
Why Other Options Are Wrong:
“Only 1” or “Only 2” — each ignores that both statements hold.
“Both incorrect” — contradicts fundamental static semantics.
Common Pitfalls:
- Attempting to read or write non-static members in a static function without passing an object.
- Confusing static member functions with free functions in the same namespace.
Final Answer:
Both 1 and 2 are correct.