Search code examples
c++compiler-constructionvirtualportability

Is this C++ code portable?


struct A {
  int a;
  virtual void print() {}
};

struct B : A {
  int b;
  virtual void print() {}
};

int main(void)
{
  A *a = new B;
  a[0].print(); // g++, vs2010, clang call B::print.
}

All three g++, vs2010, clang call B::print. Almost doubting my C++ 101. I was under the impression that using a dot with an object does not result in a dynamic dispatch. Only -> with a pointer and dot with a reference will result in a dynamic dispatch.

So my question is whether this code is portable?


Solution

  • a[0] is the same as *a, and that expression is a reference to an A, and virtual dispatch happens through references just as it does through pointers. a->print() and (*a).print() are entirely identical.