ProgrammingVery hardProduct company interview · GATE level
What happens with this code?
What happens with this code?
class B {
public:
virtual void f() { cout << "B"; }
};
class D : public B {
private:
void f() override { cout << "D"; }
};
int main() {
D d;
B& b = d;
b.f(); // L1
d.f(); // L2
}- A. It compiles and prints BD
- B. L1 fails to compile because D::f is private
- C. It compiles and prints DD
- D. L2 fails to compile; with L2 removed the program prints D
Correct answer: D. L2 fails to compile; with L2 removed the program prints D
Access is checked at compile time against the static type used in the call. Through B&, f is public in B, so L1 compiles, and at run time virtual dispatch still reaches D::f even though D made it private: it prints D. Through d, the name f refers to D::f, which is private, so L2 is an error.
More OOP with C++ and Java questions
- 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…
- Which lines fail to compile? cpp struct A { explicit A(int) { } }; struct B { B(int) { } }; void takeA(A) { } void takeB(B) { } int main()…
- What is printed? cpp struct N { int v = 0; N& operator++() { cout << "pre "; ++v; return this; } N operator++(int) { cout << "post "; N t…