Mostly, though the struct
and typedef
are unnecessary. Better written in C++ as:
class Foo {
public:
Foo(Dog dog, Cat *cat) : d(dog), c(cat) {}
private:
Dog d;
Cat *c;
};
Line-by-line:
class Foo {
The same as struct Foo
. The only difference in C++ between a class
and a struct
is that a struct
's members are public by default, while a class
's members are private. But we need some public members somewhere, so we get around that with...
public:
Everything after this is public, and can be accessed by anyone with a Foo
object.
Foo(Dog dog, Cat *cat) : d(dog), c(cat) {}
This is the constructor for Foo. It makes a new Foo
object, given a Dog
and a Cat *
. The : d(dog), c(cat)
is an initializer list. It is the same as this->d = dog; this->c = cat;
except probably faster. If you didn't want to do it that way, you could leave off the this->
unless there was a naming conflict somewhere. The {}
is the function body, empty because we moved the assignment to the initializer list.
private:
Opposite of public:
. Things declared after this can only be accessed inside our class, and are for internal use only.
Dog d;
Cat *c;
These are the class's internal variables, like the members of a struct
.