ProgrammingHardWipro · Cognizant pattern
What is printed?
What is printed?
struct Base {
static void hello() { std::cout << "Base::hello"; }
};
struct Derived : Base {
static void hello() { std::cout << "Derived::hello"; }
};
int main() {
Base *p = new Derived();
p->hello();
}- A. Derived::hello
- B. Compilation error: cannot call static via pointer
- C. Both
- D. Base::hello
Correct answer: D. Base::hello
Static member functions are never virtual, even if called through a pointer with -> syntax; the call is resolved at compile time purely from the pointer's STATIC type (Base*), so Base::hello() is called regardless of the pointed-to object's dynamic type.
More OOP with C++ and Java questions
- What is printed? cpp struct Base { virtual Base clone() { std::cout << "Base::clone "; return new Base(this); } }; struct Derived : Base {…
- What is printed? cpp class Base { public: Base() { std::cout << "Base() "; } virtual void show() { std::cout << "Base::show"; } }; class…
- What is printed? cpp class Complex { double re, im; public: Complex(double r, double i) : re(r), im(i) {} Complex operator+(const Complex&…
- What is printed? java interface Calculator { int calculate(int a, int b); } public class Main { public static void main(String[] args) {…
- What is printed? java class Matrix { int[][] data; Matrix(int[][] d) { data = d; } Matrix add(Matrix other) { int[][] r = new…
- What is printed? java class Vehicle { private int speed; protected void setSpeed(int s) { speed = s; } int getSpeed() { return speed; } }…