ProgrammingVery hardProduct company interview · GATE level
What is printed?
What is printed?
struct A {
A() { }
A(const A&) { cout << "C"; }
A& operator=(const A&) { cout << "="; return *this; }
};
void f(A a) { }
void g(const A& a) { }
int main() {
A x;
A y = x;
A z(y);
z = x;
f(x);
g(x);
A w;
w = y = z;
}- A. CC=CC==
- B. C==C==
- C. CC=C==
- D. CC=C=
Correct answer: C. CC=C==
A y = x creates a new object, so it is copy initialisation and calls the copy constructor, as does A z(y). z = x assigns to an existing object: operator=. Passing x by value to f copies it (C); passing by const reference to g copies nothing. w = y = z is two assignments, right to left. The '=' sign in a declaration never calls operator=.
More OOP with C++ and Java questions
- What is printed? cpp struct B { virtual void f() = 0; }; void B::f() { cout << "B"; } struct D : B { void f() override { cout << "D"…
- What is printed? cpp struct C { static int n; C() { n++; } ~C() { n--; } }; int C::n = 0; void f(C c) { } int main() { C a; f(a); f(a); {…
- What is printed? cpp struct S { void f() { cout << "N"; } void f() const { cout << "C"; } }; void call(const S& s) { s.f(); } int main() {…
- 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…