1
#include <iostream>
using namespace std;

class a {
  virtual int foo() {
    return 0;
  }
};

class b {
  int foo() {
    return 0;
  }
};

int main() {
  cout << sizeof(b) << endl;
  cout << sizeof(a) << endl;
}

Output (with g++ 4.9, -O3):

1
8

I assume the increase in size is due to adding a vpointer. But I thought the compiler would see that a is not actually deriving or being derived from anything, hence there is no need to add the vpointer?

2
  • 4
    It is not marked final, so how could the compiler see that it is not being derived from, say in another file? Commented Dec 5, 2016 at 23:08
  • I thought the developer would see that it is not actually deriving or being derived from anything, why there is a need to add virtual keyword to class? Commented Dec 5, 2016 at 23:19

2 Answers 2

6

The vpointer is needed because the compiler cannot guarantee an external (e.g. shared) library does not use a derived type. The existence-of-derived-class resolution happens at runtime.

Sign up to request clarification or add additional context in comments.

3 Comments

Imagine if that file contained int j (a& bar) { return bar.foo(); } -- how would the compiler make that work?
Is that a rhetorical question?
Yes. My point is the same as yours -- the compiler has no idea what code it can't see might do.
1

Run-time type information. Any polymorphic class creates extra meta-data in the program to make things like typeof and dynamic_cast work. This is in addition to the virtual function table.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.