late days - you don’t have to ask or tell us
common error from Monday: scope & lifetime
hw2 out, due in two weeks
sections tomorrow: C++ I - const, references, inlining
read “C++ Primer” for details—we won’t have time in class to cover everything useful
operator overloading
references
classes
#include <iostream>
#include <cstdlib>
int main(int argc, char **argv) {
const char *s = "hello";
int x = 42;
std::cout << s << " " << x << std::endl;
return EXIT_SUCCESS;
}
std
<<
, cout, endlq: how does g++ implement this?
#include <stdio.h>
struct stream {
FILE *fp;
};
stream print_int(stream os, int x) {
...
}
int main(void) {
stream out = {stdout};
print_int(out, 42);
}
#include <iostream>
void swap(int *x, int *y) {
int t = *x;
*x = *y;
*y = t;
}
int main(int argc, char **argv) {
int a, b;
std::cin >> a >> b;
if (!std::cin) {
std::cerr << "invalid input!" << std::endl;
return -1;
}
swap(&a, &b);
std::cout << a << " " << b << std::endl;
}
#include <iostream>
void swap(int &x, int &y) {
int t = x;
x = y;
y = t;
}
int main(int argc, char **argv) {
int a, b;
std::cin >> a >> b;
if (!std::cin) {
std::cerr << "invalid input!" << std::endl;
return -1;
}
swap(a, b);
std::cout << a << " " << b << std::endl;
}
& (ampersand): address-of or reference
client passes in an argument with normal syntax
function uses reference parameters with normal syntax
modifying a reference parameter modifies the caller’s argument
1 int x = 5, y = 10;
2 int &z = x;
3 z += 1;
4 x += 1;
5 z = y;
6 z += 1;
q: what are the values of x, y, and z at each line?
q: how does g++ implement this?
bool CalcArea(int width, int height, int *area) {
if (width < 0 || height < 0) return false;
*area = width * height;
return true;
}
...
int w = 10, h = 20, a;
CalcArea(w, h, &a);
bool CalcArea(int width, int height, int &area) {
if (width < 0 || height < 0) return false;
area = width * height;
return true;
}
...
int w = 10, h = 20, a;
CalcArea(w, h, a);
see also: C#’s ref
and out
a reference acts like an alias for some other variable
alias: another name that is bound to the aliased variable
mutating a reference is mutating the referenced variable
class declaration syntax (often in a .h file)
class Name {
private:
members;
public:
members;
};
class member definition syntax (in a .cc file)
returntype classname::methodname(parameters) {
statements;
}
You can name your .cc/.h files anything
#pragma once
class Point {
public:
Point(const int x, const int y); // constructor
int get_x() const { return x_; } // inline member function
int get_y() const { return y_; } // inline member function
double Distance(const Point &p) const; // member function
private:
int x_; // data member
int y_; // data member
}; // class Point
Point operator +(Point a, Point b);
q: what does each of the 8 const
s mean?
finish point.cc
struct
struct
and class
are (almost) the same
Write a C++ program that
Write a C++ program that:
<<
, =
, and a copy constructorconst
in all the right placesMapReduce