Course 6 – Static, vector, and working with files

Static

In the previous post, we discussed about classes. Each class instance will have its own variable (the application will allocate memory space for those variables, for each instance we have).

For example:

And we have two class instances, each with its variable:

We see that each variable is different.

When we want to have one variable for ALL instances of a class, we call it static.

Yeah, that last line…we need it to compile our application. All static objects need to have an initialization, outside of the class implementation.

Okay, let’s change its value now:

We can access the static through any instance of our class – but that can be confusing (we can access non-static members like this as well).

So we can differentiate between these two, we usually use the class name to access static members and functions. (see last line).

A static function is similar to a normal function….the difference is that you don’t need an instance of the class to call it.

and now we can use the statics without having instances of that class.

We can also use static inside functions, for variables. With this, we can persist a value of a variable throughout function calls.

If we had a normal situation, such as below, the output will always be 0:

But if we want to persist a value, we make it static.

The code below will print 0123, for example:

Working with files

When we need to work with files, we need to include the fstream header.

Writing to file

Writing to file is easy, we open the file and write to it, like we’d do with cout.

Reading from file

Reading from file is more complex than writing to it. We need a variable to store the line we read from file.

Containers – vector

A vector is a container of data.

Pretty straight-forward to use, but we need to include the vector header. We also need to specify the data type we need to store inside it.

Ok, new stuff. push_back is a function that adds entries in the container.

And that for ? It iterates through the container (visit all entries one by one) and do something for each item.

The reference symbol (&) means that the object called item is the same as the one from the container – no copies are made, so if wee modify it inside the for loop, it will modify it in the container as well – since there’s only one object.

If we don’t add &, we will make copies, so if we modify them in the for loop, we don’t change the original value (the one stored in container).

More about &, in the next course.

Homework

Read from a file, add each line into the container. Take each line in the container and reverse it.

eg. “Some text” should be “txet meoS”.

Afterwards, write the new text in a new file.

 

Also important:

  • Learn how to open an existing file, and to append data, or to overwrite the data when you open it.
  • Treat error cases – maybe the file does not exist? maybe it couldn’t be opened for some reason?

Good luck!

You may also like...