Are structures and classes really equivalent in C++?

  • A+

Assuming that struct is similar to class except for the default member privacy, why the following code does not compile?

#define class struct #include <iostream>   int main() {      return 0; } 


In file included from /usr/include/c++/7/bits/stl_algobase.h:61:0,                  from /usr/include/c++/7/vector:60,                  from main.cpp:5: /usr/include/c++/7/bits/cpp_type_traits.h:86:18: error: ‘struct std::_Sp’ is not a valid type for a template non-type parameter    template<class _Sp, class _Tp>                   ^~~ compilation terminated due to -Wfatal-errors. 


The behaviour of your code is undefined: The C++ standard does not permit the redefinition of keywords.

Perhaps the specific failure is due to template<class T> being valid syntax but template<struct T> is not? The preprocessor step seems to have ruined the implementation of <iostream> on your platform.

(A class and struct are the same in all respects aside from the default access of member variables and functions - including inheritance, as you point out.

The C++ standard allows you to forward declare as a struct and implement as a class and vice-versa, although some compilers; older versions of MSVC for example; disallow that.)


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: