The default access level for classes is private
, while for structs it is public
.
The default inheritance type is private
when deriving a class, and public
when deriving a struct.
In other words, deriving a class from a struct or class is private
by default, while deriving a struct from a class or struct is public
by default.
Contrast the two examples below. In the first, a struct is derived from a class (public inheritance).
#include <iostream> class C { public: void doStuff() { std::cout << "Doing stuff" << "\n"; } }; struct S : C // This is public inheritance { }; int main() { S s; s.doStuff(); }
In the second a class is derived from a struct (private inheritance).
#include <iostream> struct S { void doStuff() { std::cout << "Doing stuff" << "\n"; } }; class C : S // This is private inheritance { }; int main() { C c; c.doStuff(); }
The first example will compile, while the second produces the following error with g++:
class_vs_struct.cpp: In function ‘int main()’: class_vs_struct.cpp:5:10: error: ‘void S::doStuff()’ is inaccessible void doStuff() ^ class_vs_struct.cpp:18:15: error: within this context c.doStuff(); ^ class_vs_struct.cpp:18:15: error: ‘S’ is not an accessible base of ‘C’