"sb" <sp**********@yahoo.com> wrote...
Here is a different example, closer to what I want to do. I want to
have a class that models "relations" between objects. "add" adds a
relation, "check" checks if the relation exists:
#include <algorithm>
#include <vector>
#include <iostream>
class Base {
std::vector<Base*> relations;
public:
void add(Base* p) { relations.push_back(p); }
bool check(Base* p) {
return std::find(relations.begin(), relations.end(), p) \
!= relations.end();
}
};
class Derived1 : public Base {
// other members
};
class Derived2 : public Base {
// other members
};
class Derived2x : public Derived2 {
// other members
};
int main() {
Derived1 d1;
Derived2x d2x;
Derived2* p = &d2x;
d1.add(&d2x);
std::cout << d1.check(p) << '\n'; // always true ?
}
On my system, without any "other members", this is true.
And _with_ "other members"? Hint: shouldn't be any difference.
I am not sure what you're asking about. 'p' and '&d2x' share
a common trait: a base class (both Derived2 and Derived2x have
'Base' as a base class). If you convert Derived2* to Base* or
Derived2x* to Base*, you are supposed to get the same exact
part of the object if you're dealing with the same object. It
is like you have
+----------------+
| Derived2x |<-- this is where &d2x points
| +------------+ |
| | Derived2 |<+-- this is where 'p' points
| | +--------+ | |
| | | Base |<+-+-- this is what you get when either of
| | | | | | them is converted to Base*
| | +--------+ | |
| +------------+ |
+----------------+
You began with the same object (d2x in your program). Its
address is '&d2x'. 'p' is a pointer to its 'Derived2' subobject.
Whether you convert the original '&d2x' or 'p' to 'Base', you
will get the same subobject (one directly, the other indirectly).
Victor