LearnFrenzy
Sign in Take a free test

Abstract Classes and Interfaces · Predict the Output · Question 7

Do two interface pointers to one object compare equal? Answer, explanation & discussion

  • Output
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following C++ program on a 64-bit system?

main.cpp
#include <iostream>

struct I1 { virtual ~I1() = default; };
struct I2 { virtual ~I2() = default; };
struct Obj : I1, I2 {};

int main() {
    Obj o;
    I1* p1 = &o;
    I2* p2 = &o;
    std::cout << (static_cast<void*>(p1) == static_cast<void*>(p2)) << ' '
              << (p1 == &o) << ' ' << (p2 == &o) << ' '
              << (dynamic_cast<void*>(p2) == static_cast<void*>(&o)) << '\n';
    return 0;
}
  • A 0 1 1 1 Correct
  • B 1 1 1 1
  • C 0 1 0 1
  • D 0 0 0 0
Correct Answer: Option A

The I2 subobject lives at a different address, so the raw addresses differ. Comparing with &o converts &o to the matching base pointer first, so both are equal; dynamic_cast<void*> recovers the start of the complete object.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links