← Back to archive

Stdle #49 · virtual · 2026-07-25

What does this C++ snippet output?

A past puzzle — fully playable. 4 attempts, hints on wrong guesses.

#include <iostream>
struct Visitor;
struct A {
virtual int accept() { return 1; }
};
struct B : A {
int accept() override { return 2; }
};
int total(A** arr, int n) {
int s = 0;
for (int i = 0; i < n; i++) s += arr[i]->accept();
return s;
}
int main() {
A* arr[] = { new A(), new B(), new B() };
std::cout << total(arr, 3) << "\n";
}
Virtual
4 attempts left

Answer & explanation