ProgrammingHardMicrosoft/Google SDE MCQ · GATE CS
Which statement about virtual functions and templates in C++ is correct?
- A. A member function template can be virtual if it is also pure
- B. A class template's ordinary member functions can be virtual, but a member function template cannot
- C. Virtual functions are not allowed inside class templates
- D. A member function template becomes virtual when the base declares one with the same name
Correct answer: B. A class template's ordinary member functions can be virtual, but a member function template cannot
A vtable needs a fixed set of slots, but a member function template could be instantiated for unboundedly many types, so it cannot be virtual. Ordinary member functions of a class template can be virtual, since each instantiation has a fixed set.
More OOP with C++ and Java questions
- What is printed? cpp struct B { B() { cout << "B"; } B(const B&) { cout << "c"; } }; struct D : B { D() { cout << "D"; } D(const D&) {…
- What is printed? cpp struct P { int x; explicit P(int v) : x(v) { } explicit operator bool() const { return x != 0; } }; int main() { P…
- Which of the marked lines are compile errors? cpp int g(int x) { return x; } double g(int x) { return 2.0 x; } // line 1 void h(int x) { }…
- What is printed? java Map<String, Integer> m = new HashMap<>(); System.out.print(m.put("a", 1)); System.out.print(m.put("a", 2))…
- What is printed? java Map<String, Integer> m = new HashMap<>(); m.merge("k", 5, Integer::sum); m.merge("k", 5, Integer::sum); m.merge("k"…
- What is printed? java TreeMap<Integer, String> t = new TreeMap<>(); for (int k : new int[]{40, 10, 30, 20}) t.put(k, "v")…