CPP as a second language

First C++ program

Overview

Teaching: 5 min
Exercises: 5 min
Questions
  • How do you create a C++ program?

Objectives
  • Create, compile, and run your first C++ program

Here we will create our first C++ program and dissect its components and in doing so will introduce some important concepts that we will dive into in more detail as we go.

Creating a first C++ program

$ nano hello.cpp
#include <iostream>

int main(){
  std::cout<<"Hello, world!\n";
}

hello.cpp

Use the GNU C++ compiler g++ from the GNU Compiler Collection (GCC) to build it:

$ g++ hello.cpp -o hello
$ ./hello
Hello, world!

Dissecting your first C++ program

Objects and classes

Namespaces

Operators

Nano line numbers

When compiling programs a compiler usually reports errors it encounters by line number so it is particularly important to be able to find a particular line in your editor.

There are a couple ways that nano can display line number/column information. Which methods are available will depend on your version of Nano.

  1. While in nano press alt+c to display line number and column information for the line the cursor is currently on. This works for this particular nano session and on the version of nano on our training cluster.

  2. Line numbers can be toggled on/off using alt+shift+#. This is nice, but only works on newer versions of nano.

  3. When starting nano the -l option can be used to tell nano to display line numbers along the left hand side. Again only works with newer versions of nano.

  4. Tell nano to always display line numbers and current line information:

    $ nano ~/.nanorc
    

    and enter the following two lines and save and exit

    set linenumbers
    set constantshow
    

    Note that set linenumbers will only work on newer versions of nano while set constantshow will work on older versions of nano also.

Useful Nano shortcuts

Here are some shortcuts that are helpful while editing text in nano

What is a class?

Is a class:

  1. a variable which can have multiple members like a struct

  2. an object which can have multiple members like a struct

  3. a datatype which can have multiple members like a struct

  4. a datatype which can contain only a single value like int,float,etc.

Solution

  1. NO: while a class can have multiple members like a struct, a class defines a new datatype where as a variable or object are the instantiation of that class or datatype.

  2. NO: while an object has a class type, the object is not the class its self.

  3. Yes: a class is a kind of datatype that can have multiple members.

  4. No: classes can have multiple members, it is possible that they only have one member but they are not restricted to holding a single value.

Key Points