Uni Graz logo

CMS

Introduction to Basic C++ for Programmers — Part 2

Gerald Senarclens de Grancy <cms@senarclens.eu>

Terminology

Pass by Value

by_value.cpp  
/**
 * Demo for pass by value.
 * Copyright 2015 Gerald Senarclens de Grancy <oss@senarclens.eu>
 */

#include <iostream>


void pass_by_value(int i) {
  i = 5;
  std::cout << "i: " << i << " (at end of called function)" << std::endl;
}


int main() {
   int i = 3;
   std::cout << "i: " << i << std::endl;
   pass_by_value(i);
   std::cout << "i: " << i << " (after returning from function)" << std::endl;
   return 0;
}  
i: 3
i: 5 (at end of called function)
i: 3 (after returning from function)

Pass by Reference

by_reference.cpp  
/**
 * Demo for pass by reference.
 * Copyright 2015 Gerald Senarclens de Grancy <oss@senarclens.eu>
 */

#include <iostream>


void pass_by_reference(int& i) {
  i = 5;
  std::cout << "i: " << i << " (at end of called function)" << std::endl;
}


int main() {
  int i = 3;
  std::cout << "i: " << i << std::endl;
  pass_by_reference(i);
  std::cout << "i: " << i << " (after returning from function)" << std::endl;
  return 0;
}  
i: 3
i: 5 (at end of called function)
i: 5 (after returning from function)

Copy Assignment

copy_assignment.cpp  
#include <iostream>
#include <vector>

template <class Type>
void print_vector(std::vector<Type>& v) {
  for (Type& elem : v) {
    std::cout << elem << " ";
  }
  std::cout << std::endl;
}

int main() {
  std::vector<int> v1(5);
  std::vector<int> v2 = v1;  // this is copy assignment, not a reference
  std::vector<int>& v3 = v1;  // this is a reference
  v1[1] = 7;
  v2[3] = 2;
  v3[2] = 4;
  print_vector(v1);
  print_vector(v2);
  print_vector(v3);
}
  
0 7 4 0 0
0 0 0 2 0
0 7 4 0 0

Build Tools

Programming Infrastructure

Summary

Homework and Required Reading

  1. Do the 11th homework

Questions
and feedback...

Further Reading

cplusplus.com C++ Language Tutorial http://www.cplusplus.com/doc/tutorial/ (2014)
Bjarne Stroustrup Programming – Principles and Practice Using C++ Addison Wesley (December 15, 2008)
Mark Allen Weiss Data Structures and Algorithm Analysis in C++ Pearson (2013)