ProgrammingVery hardMicrosoft/Google SDE MCQ · GATE CS
What happens?
What happens?
class Shape {
public:
virtual double area() const = 0;
};
class Square : public Shape {
double s = 2;
double area() const override { return s * s; } // private in Square
};
int main() {
Square q;
Shape& r = q;
cout << r.area();
}- A. Compile error: area() is private in Square
- B. Compile error: Square is still abstract
- C. It prints 4
- D. It throws at run time because access is violated
Correct answer: C. It prints 4
Access is checked against the static type used in the call: Shape::area is public, so r.area() is allowed, and virtual dispatch then runs Square's override even though it is private there. Calling q.area() directly would not compile.
More OOP with C++ and Java questions
- What is printed? cpp struct Counter { int n = 0; Counter& add(int k) { n += k; return this; } Counter addCopy(int k) { n += k; return…
- Which statement about virtual functions and templates in C++ is correct?
- 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))…