ProgrammingHardProduct-company MCQ pattern
What is printed?
What is printed?
class Base {
public:
Base() { hello(); }
virtual void hello() { cout << "B"; }
};
class Derived : public Base {
public:
Derived() { hello(); }
void hello() override { cout << "D"; }
};
int main() { Derived d; }- A. D
- B. DD
- C. BD
- D. BB
Correct answer: C. BD
While Base's constructor runs, the object is still a Base, so virtual calls resolve to Base::hello (B). In Derived's constructor the dynamic type is Derived (D). Java behaves differently: it would dispatch to the derived override even from the base constructor.
More OOP with C++ and Java questions
- What is printed? cpp struct A { A() { cout << "A"; } }; struct B : virtual A { B() { cout << "B"; } }; struct C : virtual A { C() { cout…
- How many of these statements about C++ friend functions are correct? (i) A friend function can access the private members of the class…
- Interfaces A and B both declare default void hello(). What happens with class C implements A, B { } ?
- How many of these are correct in Java (8 or later)? (i) An abstract class can have a constructor. (ii) An interface can declare instance…
- What is printed? java // static methods of the main class: static void f() { try { System.out.print("1"); throw new…
- What is printed? java String s1 = "Java"; String s2 = "Ja" + "va"; String part = "Ja"; String s3 = part + "va"; System.out.print((s1 ==…