Reputation: 785
I just tested this out using qobject_cast (but I imagine it'd be the same for any other sort of type cast), and apparently casting an object to a different type does not change its address. This makes me think that information about the type of an object is stored elsewhere...is that correct?
I'm still new to C++, so if this makes no sense at all feel free to tell me that as well. Any help is appreciated.
Upvotes: 1
Views: 272
Reputation: 7873
In some cases, typecasting actually does change the apparent address of the source object. The original source object's address doesn't change, but the address of "that same object" (not a newly-constructed converted object) may be different if an object, reference, or pointer to a derived class is cast via static_cast
or dynamic_cast
to a reference or pointer to a base class, when the derived class inherits the base class in a multiple-inheritance hierarchy and the base classes either contain data or are polymorphic (or both). The "different address" is actually the address within the source object where the base class portion of the overall derived class resides.
Upvotes: 1
Reputation: 238351
Why does typecasting an object not change its address?
Because typecasting has absolutely zero effect on the source object1. Type casting always produces a new object (of possibly different type) or a reference. Furthermore, there is no operation that could change the address of any object. An object is stored in one address throughout its entire lifetime.
If the result of a type cast is a reference, then that reference may refer to another object in different address, in particular when converting to a reference to a type in same inheritance hierarchy.
1 Technically, a converting constructor or a conversion operator could modify the source object, but that would be horribly non-conventional.
Where is information about the object's type stored?
Type information is "stored" by the compiler while it is compiling the program. In general, the information does not need to be stored by the program itself.
In particular case of polymorphic types, some information about the type of an object is stored in the memory of the program to support dynamic_cast
and dynamic typeid
. It is stored in whatever place the language implementation has chosen appropriate.
I just tested this out using qobject_cast
There is no such thing as qobject_cast
in C++. Perhaps you are using some library.
Upvotes: 3