Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ comparing pointers to different types?

I'm having a really hard time finding information about these kind of stuff! :(

I'm confused why this isn't working:

vector<B*> b;
vector<C*> c;
(B and C are subclasses of A) 
(both are also initialized and contain elements etc etc...) 

template <class First, class Second>
bool func(vector<First*>* vector1, vector<Second*>* vector2)
   return vector1 == vector2; 

When compiling this returns:

Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast

I don't see why this wouldn't work, pointers hold addresses yeah? So why don't it just compare if the two vector pointers... point to the same address(-es)?

like image 267
optional Avatar asked Aug 08 '13 12:08

optional


1 Answers

Here's a simple example where what you're asking for won't work.

struct A{ int i; };
struct OhNoes { double d; };
struct B: public A {};
struct C: public OhNoes, public B {};

So here, B and C are both subclasses of A. However, an instance of C is unlikely to have the same address as its B subobject.

That is, this:

C c;
B *b = &c; // valid upcast
assert(static_cast<void*>(b) == static_cast<void *>(&c));

will fail.

like image 98
Useless Avatar answered Sep 30 '22 07:09

Useless