Lecture 25 - Why to use classes and header files?

Good morning everyone,

I have a question about classes and header files. In lecture 24 and 25 we create a class and a header file. But I don’t quite understand why we use them. I’m currently in lecture 29 and I thought that it would be more clear. But I still don’t understand it

For example:
In the FBullCowGame header file I have:

public:
   int getMaxTries();

private:
   int myMaxTries = 5;

In the FBullCowGame class we have the function: GetMaxTries() that returns myMaxTries. In the Main.Cpp file we call that function to get the max tries that the user has.

But why can’t I create a function in the main.cpp file where I get the maxTries?

For example:

int getMaxTries()
{
	int maxTries = 5;

	return maxTries;
}

And call that function in the playGame() function.

I don’t understand why to make a new class and header file when you get the same result with a function in the main.cpp file.

I hope someone can explain it.

Thanks!

Even with a simple game like Bulls and Cows it’s good practice to get used to separating your declarations and definitions, as well as controlling access to your member variables that hold game data. Yes, you could drop everything into main.cpp, but in real practice, you would have entirely too much code to maintain in one file, not to mention that you would have no control on how your code is accessed or packaged. One thing to think about, and it will become more clear with a larger game, is that the various classes you create will be designed to focus on specific parts of the project, e.g. player controller or level UI features.

There are many reasons to break these discrete features up, but this is the basic idea of encapsulation, a fundamental of object oriented programming, which was talked about briefly in a earlier lecture video. Check out this Data Encapsulation explanation to get a better idea of what we’re trying to achieve.

One last thing to consider is that having a header file which doesn’t include implementation is how other people will be able to use your classes without knowing how your code is written. This is the “black box” of programming, also called abstraction. You can package your code into a DLL or whatever so that it’s not legible, but people will know how to you use your methods based off of the signatures in your declarations.

I hope that helps to answer your questions.

4 Likes

Thanks for your time! I think that I start to understand it. Of course it will take some time to learn everything and I will get more and more experience through the course.

You the real MVP.

Privacy & Terms