Can I simply cast a Parent-struct in a child-struct in c++?
I tried to cast:
Base s;
Child tmp = (Child)s;
and got this error: No matching conversion for C-style cast from ...
Can anyone help me to solve this error?
Can I simply cast a Parent-struct in a child-struct in c++?
I tried to cast:
Base s;
Child tmp = (Child)s;
and got this error: No matching conversion for C-style cast from ...
Can anyone help me to solve this error?
A struct is a type consisting of a sequence of members whose storage is allocated in an ordered sequence If the sequence is a mismatch, the conversion may not work.
Within a struct object, addresses of its elements (and the addresses of the bit field allocation units) increase in order in which the members were defined. A pointer to a struct can be cast to a pointer to its first member (or, if the member is a bit field, to its allocation unit). Likewise, a pointer to the first member of a struct can be cast to a pointer to the enclosing struct. There may be unnamed padding between any two members of a struct or after the last member, but not before the first member. The size of a struct is at least as large as the sum of the sizes of its members.
First of all, If you are using c++. Why would you like to perform c style casting between Base
and Child
?
C++ provided static_cast
for non-polymorphic conversion and dynamic_cast
for the polymorphic conversion.
There is more info about these casts: Regular cast vs. static_cast vs. dynamic_cast?