ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
struct S {
void f() { cout << "N"; }
void f() const { cout << "C"; }
};
void call(const S& s) { s.f(); }
int main() {
S a;
const S b{};
S* p = &a;
const S* q = &a;
a.f(); b.f(); p->f(); q->f(); call(a);
}- A. NCNNN
- B. NCNCC
- C. NCNCN
- D. NNNNN
Correct answer: B. NCNCC
Overloads on const are chosen by the static type of the object expression, not by whether the object itself was declared const. a and *p are non-const, so N. b is const, and *q and the parameter s are accessed through pointer- or reference-to-const, so the const overload runs even though q and s refer to the non-const a.
More OOP with C++ and Java questions
- What is printed? cpp struct B { void f(int) { cout << "Bi "; } void f(double) { cout << "Bd "; } }; struct D : B { using B::f; void f(int)…
- What happens with this code? cpp class B { public: virtual void f() { cout << "B"; } }; class D : public B { private: void f() override {…
- What is printed? cpp struct B { virtual const char who() const { return "B"; } }; struct D : B { const char who() const override { return…
- What is printed? cpp struct A { int v = 0; A() { cout << "A"; } }; struct B : A { B() { cout << "B"; } }; struct C : A { C() { cout <<…
- What is printed? cpp void f(bool) { cout << "bool "; } void f(std::string) { cout << "string "; } void g(int) { cout << "int "; } void…
- What is printed on a typical platform (16-bit short, 32-bit int)? cpp int i = -1; unsigned int u = 1; short s = -1; unsigned short us = 1…