Constructing Objects
In the code for main.cpp
below, the highlighted lines construct objects of the Cow
class.
main.cpp
:
...
int main() {
Cow bessie{3, 12};
const Cow mabel{1, 2};
// This line wouldn't work!
// Cow duke;
bessie.moo(1);
mabel.moo(2);
bessie.setAge(4);
// This line wouldn't work!
// mabel.setAge(2);
return 0;
}
Perhaps you've noticed that the syntax is a little different than Java's and Python's syntax.
Curly Brace Initialization
Notice that we wrote
Cow bessie{3, 12};
const Cow mabel{1, 2};
with curly braces ({}
), and not
Cow bessie(3, 12);
const Cow mabel(1, 2);
Hay, yeah, I did notice that. Why? What does it mean?
I think it means MORE syntax!! MORE ways to do things!
Both ways work, but the curly brace form is stricter. Normally, C++ performs conversions and promotions on arguments passed in parentheses, but the brace form for constructor arguments only allows promotions, not conversions. This stricter rule can reveal coding errors.
In CS 70, we use the stricter curly brace form unless there is some compelling reason not to.
No Equal Sign
Also I noticed that there's no equal sign. In Java I'm used to something like
Cow bessie = new Cow(3, 12);
where you declare a variable and assign to it all at once.Yes, that's true! You can see that to initialize an object, you just declare it and pass parameters in as
Cow bessie{3, 12};
. No assignment necessary!You will see later on that there is actually a C++ statement that is analogous (and syntactically similar) to the usual Java instantiation syntax. It's just that there's something going on in that Java statement that we haven't discussed in C++ yet.
For now, it's important to just commit this idiom for instantiation to memory, so you don't accidentally slip into a Java accent!
What's wrong with my accent?! My accent is fine!! Fine!!!
Remember: When we declare and initialize an object, there is no need for an equal sign!!
Examples of object initialization:
Sheep mead;
Dog doug{true};
Equal signs: 0
Phew! We've done a lot! Let's head up to the parent page, take a look at our progress so far, and maybe take a break before we continue on.
(When logged in, completion status appears here.)