Books!

Books from Bjarne Stroustrup.

Compilers

Specify c++ version using -std flag, e.g. g++ -std=c++14.

Philosophy

Hello World

// hello.cpp
#include <iostream>
using namespace std;

int main() {
  // print string using stream IO
  cout << "Hello, World!" << endl;
  return 0; // 1..63 for error
}

Compile

> g++ -std=c++14 -Wall hello.cpp -o hello
> ./hello

<< and >> operator

It means "shift left or right" to the stream.

string name = "Hello";
cout << "name = " << name << endl;
cin >> name;

Namespaces

Namespaces are used to group related items. All standard library is in std namespace.

std::string name; // this form is called `qualified name`

Classes

Classes are made up of members.

Abstraction

Encapsulation

Access Modifiers

Example: Point class

A declaration of Point class in the header file:

// `point.h`: A 2D point class
class Point {
  double x, y; // Data-members
public:
  Point(); // Constructors
  Point(double x, double y);
  ~Point(); // Destructor
  double get_x(); // Accessors
  double get_y();
  void set_x(double x); // Mutators
  void set_y(double y);
}

A definition of Point class in the cpp file:

#include "point.h"

// Default (no-argument) constructor
Point::Point() {
  x = 0;
  y = 0;
}

// Two-args constructor - sets point to (x, y)
Point:: Point(double x, double y) {
  // Because of variable shadowing, use `this` pointer
  // for resolving ambiguity of the code.
  this->x = x;
  this->y = y;
}

// Cleans up a Point object
Point::~Point() {
  // nothing to do
}

// Returns x of a Point
double Point::get_x() {
  return x;
}
double Point::get_y() {
  return y;
}
void Point::set_x(double x) {
  this->x = x;
}
void Point::set_y(double y) {
  this->y = y;
}

Usage of Point class:

#include "point.h"

Point p1;
Point p2{3, 5};
cout << "P2 = (" << p2.get_x() << ", " << p2.get_y << ")\n";
p1.set_x(210);
p1.set_y(100);

// Compiler reports an error because of the  access-level.
p1.x = 452;

std::string class

#include <string>
// with many features over `char*` string
string name;
cout << "What is your name? ";
cin >> name;
cout << "Hello " << name << ".";

string favorite_color{"green"};
string mood = "happy";
mood = "cheery";

Coming up next

Website Setting

Select website color