C++ Beginners


:: Session 1 ::

Objects, Types & Values


Programming, Principles and Practice Using C++ — Bjarne Stroustrup

Very Basic

"Hello World"


  // This program outputs the message "Hello World!"
  
  #include "stdlib.h"

  using namespace std;

  int main() 
  {
    cout << "Hello World!\n";    
    return 0;
  }
            
  • Comments begin with  // 
  •  #include  directive
  • every .cpp has a  main  function

A function has 4 parts:


  int main(x, y, z){ ... ; }
              

  1. A return type… int
  2. A name… main
  3. A parameter list… (x, y, z)
  4. A function body… { ... ; }

Objects


Input


  int x = 0;  // define variable "x" with an initial value "0"
  cin >>  x; // get the input-value and put it into x 
              

Object is a region of memory with specific type and name.

Variable is a named object…

It can be accessed through its given name
It has a specific type
The data items we put into it is called values

5 basic types:


  int n = 0;  // integer
  double d = 3.4;  // floating-point numbers
  char c = 'a';  // individual character
  string s = "apple";  // character strings
  bool t = true;  // boolean
              

">>" & "<<" are both type sensitive.

Reading of strings is terminated by whitespaces.

Operations & Operators


Operations are determined by Type

sqrt(n); isn't an operator, but a named function

Variable "n" must be a floating-point number.

operator + for strings means concatenation.

Assignment vs. Initialization

Composite assignment operators


  ++count;  // incrementation
  n += 5;   // "-=", "%=", (scaling operators "*=" & "/=")
            

Names, Types & Objects


Names Convensions

Letters, digits and underscores. Start with letter

C++ compiler is case sensitive

Reserved names, aka keywords

Choose meaningful names

Other Conventions

Fixed amount of memory for each type

int 4 bytes
double 8 bytes
char 1 byte
bool 1 byte
string different from string to string (a string tracks the number of the characters it holds)

Type Safety