C++ class templates: if you instantiate a class template once with int and again with double, how do you call the same member function on those different instantiations?
Computer Science
Object Oriented Programming Using C++
Difficulty: Easy
Choose an option
-
AYou must precede each function call with the word int or double
-
BOnce a function is used as one type, it becomes unavailable for use with the other type
-
CThere is no difference in the procedure to call a member function
-
DYou cannot perform this operation in C++
-
ENone of the above
Answer
Correct Answer: There is no difference in the procedure to call a member function
Explanation
Introduction / Context:Templates enable writing type-independent code. When you instantiate a class template with different type arguments (e.g., MyBox
Given Data / Assumptions:
- We have a class template with the same set of member functions for each instantiation.
- Two instantiations are created: one with int and one with double.
- The question concerns the procedure to call a member function on each object.
Concept / Approach:
- Each instantiation is a separate type (e.g., Box
vs Box ), but the syntax to call members is identical: object.member(args). - No language rule requires prefixing calls with the type name; overload resolution and templates handle this automatically.
- Availability of a function on one instantiation does not remove it from another; interfaces are replicated per instantiation, subject to constraints.
Step-by-Step Solution:
Create objects: BoxVerification / Alternative check:
Examine the standard library: std::vectorWhy Other Options Are Wrong:
- Prefix words int/double: Not part of call syntax.
- Becomes unavailable: False; instantiations coexist independently.
- Cannot perform: Templates are designed for exactly this usage.
Common Pitfalls:
- Assuming templates erase types at compile time like some languages; in C++, types remain distinct.
- Forgetting that constraints (e.g., operations required on T) may limit certain instantiations.
Final Answer:
There is no difference in the procedure to call a member function