- [Instructor] C++ classes
are based upon C structures.
In fact, you can create a class
using either the struct or the class keyword.
For example, I can do this.
I can say struct,
call it "a"
and I can give it some data members.
And then down here in main
I can create an object with that, call it "a" lowercase
and initialize it within the initializer list.
The column won't work.
And I may obviously need a semi-colon there
and then I can print it out with a print f like this.
And when I build and run this
you notice that I get that result.
So that is what we expect from a struct.
What's interesting is that struct and class
are effectively identical with only one difference.
If I type class here,
and obviously if I build and run this,
it won't build because these are now private data members
and they're no longer visible to the interface.
If instead I say public here,
now I can build and run this
and it works just the same as if it were a structure.
So the only difference between struct and class,
is it struct defaults to public,
and class defaults to private for all of its members.
So in a class, typically most data members are kept private
and they're accessed by public member functions
called accessors.
This practice is often called encapsulation
and it's a fundamental concept
in object oriented programming.
For example, if we take a look at accessories.cpp
I'm just going to delete this working copy here
and make a copy of accessors.cpp.
And if we take a look at this,
you see, this is exactly the same structure
but those data members are now private.
And there are now accessors,
setters and getters, member functions
for setting and getting the values.
And there's a constructor here for initializing the object.
And so down here, we have an object it's still called "a"
and we've initialized with the initializer
rather than a structure initializer list.
And I'm using the same print app
except instead of accessing the data members directly,
I'm using the getters.
And so when I build and run this,
you see we get exactly the same result.
We're going to learn more about member functions
later in this chapter,
but for now, just understand that C++ classes
are based upon C structures.
In fact, C++ structures and classes are identical
except that struct members default to public
while class members default to private.
It's good practice to use struct
when the structure will only have data members,
and to use class,
when there they're also function members.