0

I wonder if it is possible to make a pointer of (let's say) type A to point to a pointer of type B ? If it is possible then when you deference them they will show the same value? A=double B=int or viceversa?

  • This is called type casting: http://www.tutorialspoint.com/cprogramming/c_type_casting.htm – Maltysen Aug 01 '15 at 09:32
  • Lets say that i use reinterpret_cast to point pointer of type A to pointer of type B. When i dereference them they show different values even if they point to the same space in memory.How can i solve to show the same value when i deference them? – Otniel-Bogdan Mercea Aug 01 '15 at 09:35
  • Why do you want to do this? What problem are you trying to solve? – Alan Stokes Aug 01 '15 at 09:55
  • i only asked because i wanted to know the mechanism behind it.I wondered if a can point to a pointer with the same type it is possible to point to a pointer of another type.I succedd and when i display both of them i see that they have the same address.Porblem is they do not store the same value.Can i fix this? – Otniel-Bogdan Mercea Aug 01 '15 at 09:57

2 Answers2

0

If I understand correctly, you have

T* ptr1;   S* ptr2;

where T and S are two different, unrelated (by inheritance for example) types and want ptr2 to point to ptr1

ptr2 = reinterpret_cast<T*>(ptr1);

You may not do any access through ptr2, however, because it would break the strict-aliasing rule.

edmz
  • 8,220
  • 2
  • 26
  • 45
  • what do you mean by" access"? To deference? – Otniel-Bogdan Mercea Aug 01 '15 at 09:46
  • @OtnielMercea By access it's meant that you may not read or write from/through that pointer. Dereferencing is a kind of read, so yes, too. – edmz Aug 01 '15 at 09:49
  • Would you explain me why not acces through it pls? I want to understand it much deeper.Pls – Otniel-Bogdan Mercea Aug 01 '15 at 09:50
  • @OtnielMercea Have you read the answers in the other question I linked? If that's not enough (shouldn't be), take a look at [this](http://cellperformance.beyond3d.com/articles/2006/06/understanding-strict-aliasing.html) too. – edmz Aug 01 '15 at 09:56
0

This is possible only if you have a base with A and B sub classes. you can access A and B with base pointer and compiler will decide at run time which pointer to be executed.

class Base{
}

class A:Base{
}
class B:base{
}

int main(){
Base* ObjBase;
//accessing class A with Base pointer
ObjBase=new A(); 
//Accessing class B with Base pointer
ObjBase=new B();

}

This is class polymorphism . you will often need it when you want to have a single array of base class having different child classes object