Reputation: 1394
There are some features in C++ that are type safe and some other features that are not.
Example of C++ type safety:
char c = 'a';
int *p = &c; // this is not allowed (compiler error)
Example of C++ lack of type safety:
int *p; // I don't have to initialize p, and so it will have some junk/random value
*p = 12345; // this will probably lead to segmentation fault!
I have read in a couple of articles that C++ is not a type safe language. Can I consider it to be a non type safe language, or is it more accurate to say that it is a partially type safe language?
Upvotes: 3
Views: 1343
Reputation: 48615
The example you are giving is not violating "type safety" at all. Here:
Example of C++ lack of type safety:
int *p; // I don't have to initialize p, and so it will have some junk/random value *p = 12345; // this will probably lead to segmentation fault!
In that example *p
is an int
and you are assigning it the number 12345
which is also an int
.
The compiler is not allowing you to violate the type system because you are assigning one int
to another int
.
The fact that the pointer you are dereferencing to get to one of your int
s is not initialized is causing a potential crash but it has nothing to do with type safety.
This will not crash:
int* p = new int;
*p = 12345;
Here you are writing an int
(12345
) to another int
(*p
) but this time the int
you are writing to (*p
) actually exists.
It is not type safety that the compiler is failing to check it is the integrity of the pointer.
Upvotes: 2
Reputation: 145259
It's reasonable and practically meaningful to say that C++ is a partially type safe language.
C++ started as an extension of original mid- to late 1970's C, which was designed as a kind of high level portable assembly language, to make Unix more portable and easier to maintain. C++ added type safety for its new features, but with the goal of being mainly compatible with C (in particular using all those existing C libraries, including their headers) the original core of C had to be left as it was.
In particular, C++ got the decay of array to pointer from C. In C++ it isn't type safe because it allows an implicit conversion from array of Derived
to pointer to Base
, which can in turn be indexed but with Undefined Behavior.
Upvotes: 2