C++ Lesson 2 – Variables

Today we’ll be looking at variables, this includes primitive data types as well as some useful objects available in C++.

We have access to the same data types we do in C, those being:

-int
-double
-float
-bool
-char

Which can be declared as so:

In addition to these, C++ gives us access to a multitude of objects that come with C++ standard libraries, much like we’ve seen before in Java.

We can use strings, vectors<> and many other objects that were not available in C. They can be declared like so:

Strings are obviously just like strings in other languages, but vectors are a type of collection. They act somewhat akin to ArrayLists in Java that we’ve looked at before.

You can push_back elements, remove elements and even index to get/change elements in the vector:

As you can see, C and C++ has a lot of overlap, or rather most parts of C are included in C++. To put it in perspective, you can think of C++ as a superset of C, or as I like to call it, the object-oriented expansion.

This means that you can reuse a lot of C concepts in your C++ code, including comments. By default, we have access to two different comments:

-// Single line
-/**/ Multi-line

And these are written like so:

It’s prety similar to Java, just the JavaDoc comments are missing. If you want JavaDoc style comments in your code, packages exist to perform the same functionality.

Last thing to touch on today is the namespace issue. All the things we’ve looked at thus far have utilized the “std” namespac, which is why we’re “using namespace std”. It is possible to have more namespaces, which is particularly useful when using more libraries, for example the OpenCV library for image processing.

Next time

That’s it for this time, next time we’ll be looking at writing functions, so we can compartmentalize our code. We’ll examine both normal and recursive functions.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Design a site like this with WordPress.com
Get started