1

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?

  • 2
    You can, if you declared a `Child::Child(Base const &)` constructor. The C-style cast is unnecessary though, just do `Child tmp(s);`. – Quentin Jun 05 '19 at 15:53
  • 2
    No. The child may have extra members that don't exist in the base class. Where would their values come from? – interjay Jun 05 '19 at 15:53
  • 3
    "_Can I simply cast a Parent-struct in a child-struct in c++?_" No. `s` is not a `Child. Consider learning from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Algirdas Preidžius Jun 05 '19 at 15:53
  • 2
    I would highly suggest looking through the [c++ casting question](https://stackoverflow.com/q/332030/332733) C style casts are incredibly dangerous. – Mgetz Jun 05 '19 at 15:54
  • You cast on the wrong direction, a Child is a Base but not the reverse. May be also you wanted to work on pointer ? – bruno Jun 05 '19 at 16:03

1 Answers1

0

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?

Arun Kumar
  • 151
  • 3
  • 10