Posts tagged ‘cpp’

So what exactly is the difference between a class and a struct in C++? After wondering and debating internally for quite a long time, I looked around the net and found the (simple) explanation that:

"The only difference between a struct and a class is in the default access."

That is, a sruct is public by default and a class is private by default. Extending (inheriting) them is also like-wise - public inheritance for struct and private for class.

I believe struct was made public by default to be compliant with C . Thus a C struct can be used similarly in C++. i.e.

C++:
  1. struct Foo
  2. {
  3. int bar;
  4. char* baz;
  5. };
  6.  
  7. Foo makeFoo()
  8. {
  9. Foo temp;
  10. temp.bar = 1;
  11. temp.baz = "test";
  12. return temp;
  13. }

The only reason the above code will work in C++ is because of the default access of struct being public.