ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class Base {
public:
void show() { cout << "B1"; }
virtual void vshow() { cout << "B2"; }
};
class Derived : public Base {
public:
void show() { cout << "D1"; }
void vshow() { cout << "D2"; }
};
int main() {
Base *b = new Derived;
b->show();
b->vshow();
}- A. B1B2
- B. D1B2
- C. B1D2
- D. D1D2
Correct answer: C. B1D2
show is not virtual, so the call is bound at compile time by the pointer type Base*: B1. vshow is virtual, so the call goes through the vtable to the actual object, a Derived: D2.
More OOP with C++ and Java questions
- In C++, Base has a non-virtual destructor and Derived : public Base owns a heap buffer freed in ~Derived. What happens on: Base p = new…
- What is printed? java String a = "hi"; String b = "hi"; String c = new String("hi"); System.out.print((a == b) + " " + (a == c) + " " +…
- What is printed? java System.out.print('a' + 1); System.out.print(" "); System.out.print("" + 'a' + 1);
- What is printed? cpp void f(int) { cout << "int "; } void f(double) { cout << "double "; } int main() { f('a'); f(2.5f); }
- What is printed? cpp struct A { A() { cout << "C"; } A(const A &) { cout << "K"; } ~A() { cout << "D"; } }; void f(A a) { } int main() { A…
- What is printed? cpp class A { public: static int count; A() { count++; } ~A() { count--; } }; int A::count = 0; int main() { A a, b; { A…