is pointer to base always <= pointer to derived class?
c++, casting, inheritance
Solution
No. Memory layout is implementation detail.
That being said, I'm not aware of any implementation that doesn't actually do that, assuming there are no virtual functions. If you introduce a virtual function in `Derived` (but there were none in `Base`), the virtual table pointer could (depending on the implementation) be placed before the `Base` fields (making the `Base*` greater than `Derived*`).
Clarification:
The example above is Visual C++ specific. You can check it out using the following code:
class Base {
int X;
};
class Derived : public Base {
virtual void f() {
}
int Y;
};
int main() {
Derived d;
Derived* d_ptr = &d;
Base* b_ptr = dynamic_cast<Base*>(d_ptr); // static_cast would be enough BTW.
bool base_smaller_or_equal = (ptrdiff_t)b_ptr <= (ptrdiff_t)d_ptr;
return 0;
}
The `base_smaller_or_equal` will be `false` under Visual C++. Judging on @enobayram's comment, it should be `true` under GCC.
In any case, it is an implementation detail and not to be relied upon.
Problem
I wonder if it's guaranteed by the C++ standard that single inheritance make the object "grow" upward, that is given a `class Base` and a `class Derived: public Base`, and a pointer `Derived* ptr`, the result of `dynamic_cast<Base*>(ptr)` will be always numerically smaller or equal to `ptr`.