Re: Casting pointers
Juha Nieminen wrote:
Rolf Magnus wrote:
Juha Nieminen wrote:
Taras_96 wrote:
Hi everyone,
Herb Schildt in "C++, the complete reference" writes:
"In C++, it is illegal to convert one type of pointer into another
without the use of an
explicit type cast. For this reason, the preceding program will not
even compile if
you try to compile it as a C++ (rather than as a C) program. However,
the type of
error described can still occur in C++ in a more roundabout manner."
However, the following works with g++ without any errors:
Derived* pDerived = new Derived();
Base* pBase = pDerived;
Well, an object of type Derived *is* an object of type Base. Basic
object-oriented programming.
However, an object of type pointer to Derived is *not* an object of type
pointer to Base.
But since the objects they are pointing to are "of the same type", the
casting is valid (although only in the Derived -> Base direction).
The sentence that we're discussing about is: "In C++, it is illegal to
convert one type of pointer into another without the use of an
explicit type cast". And that is wrong. In the above example, the pointers
are of different type, and still they can be converted without a cast.