You are on page 1of 41

CodeCademy C++

Hello World
C++ was created by Bjarne Stroustrup and his team at Bell Laboratories in 1979. Today C++ is
used everywhere even on mars. As the name implies, C++ was derived from the C programming
language; the ++ is the increment operator in C. Bjarne’s goal was to add object-oriented
programming into the C language, which was and still is a language well-respected for its
portability and low-level functionality. It is:
 Fast and flexible
 Well supported
 A language that forces you to think in new and creative ways.
C++ programs are stored in files that usually have the file extension .cpp, which stands for “C Plus
Plus”.
Code 2/5:
#include <iostream> // include libraries

int main() { // main() function


std::cout << "Hello World!\n";
}

// single line comment


/*
Multi
Line
Comment
*/

std::cout is the “character output stream”. It is pronounced “see-out”.


<< is an input operator, likewise >> is an output operator.
“Hello World\n” is the string that is being output, strings have double quotes, \n is new line
; signifies end of statement
Code 3/5:
#include <iostream>

int main() {
// pass string to character out put stream using input operator
std::cout << "Codecademy\n";
}

Code 4/5:
#include <iostream>

int main() {
std::cout << " 1\n";
std::cout << " 2 3\n";
std::cout << " 4 5 6\n";
std::cout << "7 8 9 10\n";
}
Code 5/5:
#include <iostream>

int main() {
std::cout << "Dear Self, dont die lol, 03/07/2019\n";
}
Compile & Execute
C++ is a compiled language, which requires a compiler.
To compile a file you need o type g++ followed by the file name in the terminal:
g++ hello.cpp
It will translate the C++ program hello.cpp and create a machine code file called a.out. To
execute the machine code file, you need to type ./ + the machine code file name in the terminal
./a.out
Code 2/5:

To give the output executable file a specific name, we add -0 file_name after the compile
statement:
g++ hello.cpp –o hello
This will create a machine code file called hello which can be executed using:
./hello
Code 3/5:

Comments:
// single line
/*
Multi
Line
*/
Variables
Int, double, char ‘’, string “”, bool
In C++ variable names consist only of upper/lower case letters, digits and/or underscores.
Code 2/10:
#include <iostream>

int main() {
// Declare a variable
int year;
}

In C++ a single equal sign = does not really mean “equal”. It means “assign”.
Code 3/10:
#include <iostream>

int main() {
// Declare a variable
int year;
// Initialize a variable
year = 2019;
}

Code 4/10:
#include <iostream>

int main() {
int score = 0;
// Declare and initialize a variable here
int year = 2019;
return 0;
}

Code 5/10:
#include <iostream>

int main() {
int score = 0;
// Change score here:
score = 1234 * 99;
std::cout << score << "\n";
}
We use quotes when we want a literal string, we don’t use quotes when we refer to the value of
something with a name, like a variable. You can use multiple << operators to chain the things you
want to output.
Code 6/10:
#include <iostream>

int main() {
int score = 0;
// Output
std::cout << "Player score: " << score << "\n";
}

Just as cout is used for output, cin is used for input. The output operator >> specifies where the
input goes.
Code 7/10:
#include <iostream>

int main() {
int tip = 0;
std::cout << "Enter tip amount: ";
std::cin >> tip;
std::cout << "You paid " << tip << " dollars.\n";
}

Code 8/10:
#include <iostream>

int main() {
double tempf = 83;
double tempc = (tempf - 32)/1.8;
std::cout << "The temp is " << tempc << " degrees Celsius.\n";
}

Code 9/10:
#include <iostream>

int main() {
double tempf;
double tempc;

// Ask the user


std::cin >> tempf;

tempc = (tempf - 32) / 1.8;


std::cout << "The temp is " << tempc << " degrees Celsius.\n";
}
Code 10/10:
#include <iostream>

int main() {
double height, weight, bmi;

// Ask user for their height


std::cout << "Type in your height (m): ";
std::cin >> height;

// Now ask the user for their weight


std::cout << "Type in your weight (kg): ";
std::cin >> weight;

// calculate BMI
bmi = weight / (height*height);

// Output BMI
std::cout << "Your BMI is " << bmi << "\n";

return 0;
}
Conditionals & Logic
Code 2/8:
#include <iostream>
#include <stdlib.h>
#include <ctime>

int main() {
// Create a number that's 0 or 1
srand (time(NULL));
int coin = rand() % 2;

// If number is 0: Heads
// If it is not 0: Tails

if (coin == 0) {
std::cout << "Heads\n";
} else {
std::cout << "Tails\n";
}
}

if (condition) {statements}
Code 3/8:
#include <iostream>

int main() {
int grade = 90;
if (grade>60){
std::cout << "Pass";
}
}

Code 4/8:
#include <iostream>

int main() {
int grade = 90;

if (grade != 60) {
std::cout << "Pass\n";
}
}
Code 5/8:
#include <iostream>

int main() {
int grade = 59;

if (grade > 60) {


std::cout << "Pass\n";
} else {
std::cout << "Fail";
}
}

Code 6/8:
#include <iostream>

int main() {
double ph = 4.6;

// Write the if, else if, else here:


if (ph>7){
std::cout << "Basic";
} else if (ph < 7){
std::cout << "Acidic";
} else {
std::cout << "Neutral";
}
}
Code 7/8:
#include <iostream>

int main() {
int number = 9;

switch(number) {
case 1 :
std::cout << "Bulbusaur\n";
break;
case 2 :
std::cout << "Ivysaur\n";
break;
case 3 :
std::cout << "Venusaur\n";
break;
case 4 :
std::cout << "Charmander\n";
break;
case 5 :
std::cout << "Charmeleon\n";
break;
case 6 :
std::cout << "Charizard\n";
break;
case 7:
std::cout << "Squirtle";
break;
case 8:
std::cout << "Wartortle";
break;
case 9:
std::cout << "Blastoise";
break;
default :
std::cout << "Unknown\n";
break;
}
}
Code 8/8:
#include <iostream>

int main() {
int planetNumber;
std::string planetName; // You have to use std::string since it's in the std namespace.
double weightKg;
double newWeightKg;

std::cout << "Enter your weight on earth in kg: ";


std::cin >> weightKg;
std::cout << "Enter a number for the planet you want to fight on: ";
std::cin >> planetNumber;

switch (planetNumber){
case 1:
weightKg *= 0.78;
planetName = "Venus";
break;
case 2:
weightKg *= 0.39;
planetName = "Mars";
break;
case 3:
weightKg *= 2.65;
planetName = "Jupiter";
break;
case 4:
weightKg *= 1.17;
planetName = "Saturn";
break;
case 5:
weightKg *= 1.05;
planetName = "Uranus";
break;
case 6:
weightKg *= 1.23;
planetName = "Neptune";
break;
default:
std::cout << "Invalid input\n";
planetName = "Earth";
break;
}

std::cout << "Your weight on planet " << planetName << " is " <<
weightKg << "kg.\n";
}
Logical Operators
&& and, || or, ! not
Code 2/5:
#include <iostream>

int main() {
int hunger = true;
int anger = true;

// Write the code below:


if (hunger == true && anger == true){
std::cout << "Hangry";
}
}

Code 3/5:
#include <iostream>

int main() {
int day = 6;

// Write the code below:


if (day == 6 || day == 7){
std::cout << "Weekend";
}
}

Code 4/5:
#include <iostream>

int main() {
bool logged_in = false;

// Write the code below:


if (!logged_in){
std::cout << "Try again";
}
}

Code 5/5:
#include <iostream>

int main() {
int year;
bool leapYear = false;

std::cout << "Enter a year: ";


std::cin >> year;

if (year < 10000 && year > 999){


if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0){
leapYear = true;
}
} else {
std::cout << "Year must be a 4 digit number\n";
}

if (leapYear){
std::cout << "The year " << year << " is a leap year\n";
} else {
std::cout << "The year " << year << " is not a leap year\n";
}
}

Loops
Code 2/7:
#include <iostream>

int main() {
int pin = 0;
int tries = 0;

std::cout << "BANK OF CODECADEMY\n";

std::cout << "Enter your PIN: ";


std::cin >> pin;

while (pin != 1234 && tries <= 3) {


std::cout << "Enter your PIN: ";
std::cin >> pin;
tries++;
}

if (pin == 1234) {
std::cout << "PIN accepted!\n";
std::cout << "You now have access.\n";
}
}

While (condition) {statements}


Code 3/7:
#include <iostream>

int main() {
int guess;
int tries = 0;

std::cout << "I have a number 1-10.\n";


std::cout << "Please guess it: ";
std::cin >> guess;

// Write a while loop here:


while (guess != 8 && tries < 50){
std::cout << "Wrong guess, try again: ";
std::cin >> guess;
tries++;
}

if (guess == 8) {
std::cout << "You got it!\n";
}
}

Code 4/7:
#include <iostream>

int main() {
int i = 0;
int square = 0;

// Write a while loop here:


while (i<10){
square = i*i;
std::cout << i << " " << square << "\n";
i++;
}
}

For loop is like in Java


Code 5/7:
#include <iostream>

int main() {
for (int i = 0; i < 10; i++) {
std::cout << "I will not throw paper airplanes in class.\n";
}
}

Code 6/7:
#include <iostream>

int main() {
// Write a for loop here:
for (int i = 99; i > 0; i--){
std::cout << i << " bottles of pop on the wall.\n";
std::cout << "Take one down and pass it around.\n";
std::cout << i-1 << " bottles of pop on the wall.\n\n";
}

std::cout << "No more bottles of pop on the wall.\n";


std::cout << "No more botteles of pop.\n";
std::cout << "Go to the store and bye some more,\n";
std::cout << "99 bottles of pop on the wall.\n";
}

Vectors
A vector is a sequence of elements that you can access by index and is dynamically sized.
std::vector lives inside the <vector> header. So you must include <vector> at the top
#include is a pre-processor directive that tells the compiler to include whatever library that
follows.
To create a vector you do:
std::vector<type> name;
The type of the vector cannot be changed after declaration.
Code 2/8:
#include <iostream>
#include <vector>

int main() {
std::vector<double> subway_adult;

// Declare another vector here:


std::vector<double> subway_child;
}

Code 3/8:
#include <iostream>
#include <vector>

int main() {
std::vector<double> subway_adult = {800, 1200, 1500};

// Give subway_child some values:


std::vector<double> subway_child = {400, 600, 750};
}

Code 4/8:
#include <iostream>
#include <vector>

int main() {
std::vector<double> subway_adult = {800, 1200, 1500};

std::vector<double> subway_child = {400, 600, 750};

// What number at index 2 of subway_child?


std::cout << subway_child[2];
}

Use .push_back() function to add a new element onto the end (back) of the vector.
Use .pop_back() function to remove elements from the end (back) of the vector. Unlike in other
languages this function does not return the element that is removed.
Code 5/8:
#include <iostream>
#include <vector>

int main() {
std::vector<std::string> last_jedi;

// Add characters here:


last_jedi.push_back("kylo"); // adds to end of vector
last_jedi.push_back("rey");
last_jedi.push_back("luke");
last_jedi.push_back("finn");

std::cout << last_jedi[0] << " ";


std::cout << last_jedi[1] << " ";
std::cout << last_jedi[2] << " ";
std::cout << last_jedi[3] << " ";
}

.size() function gets size


Code 6/8:
#include <iostream>
#include <vector>

int main() {
std::vector<std::string> grocery = {"Hot Pepper Jam", "Dragon Fruit",
"Brussel Sprouts"};

// Add more
grocery.push_back("Duck");
grocery.push_back("Suck");
grocery.push_back("Fuck");

std::cout << grocery.size();


}

You can use a for loop to change the value of each element in a vector or add up the elements of
a vector.
Code 7/8:
#include <iostream>
#include <vector>

int main() {
std::vector<double> delivery_order;

delivery_order.push_back(8.99);
delivery_order.push_back(3.75);
delivery_order.push_back(0.99);
delivery_order.push_back(5.99);

// Calculate the total using a for loop:

double total = 0.0;

for (int i = 0; i < delivery_order.size(); i++){


total += delivery_order[i];
}

std::cout << total << "\n";


}

Code 8/8:
#include <iostream>
#include <vector>

int main(){
std::vector<int> vec = {2, 4, 3, 6, 1, 9};
int evenTot = 0;
int oddProd = 1;

for (int i=0; i<vec.size(); i++){


if (vec[i]%2==0){ // if even
evenTot += vec[i];
} else { // if odd
oddProd *= vec[i];
}
}

std::cout << "Sum of even numbers is " << evenTot << "\n";
std::cout << "Product of odd numbers is " << oddProd << "\n";

return 0;
}

Functions
A function is a named block of code that performs a specific task.
Code 2/10:
#include <iostream>

int main() {
// This seeds the random number generator:
srand (time(NULL));

// Use rand() below to initialize the_amazing_random_number


int the_amazing_random_number = rand() % 31;
std::cout << the_amazing_random_number;
}

Code 3/10:
return_type function_name( any, parameters, you, have ) {
// Code block here

return output_if_there_is_any;
}

A void function also known as a subroutine, has no return value.


Code 4/10:
#include <iostream>

// Define oscar_wilde_quote() below:


void oscar_wilde_quote(){
std::cout << "The highest, as the lowest, form of criticism is a mode
of autobiography.";
}

int main() {
// Call your function here:
oscar_wilde_quote();
}

Code 5/10:
#include <iostream>
// Change needs_it_support so that it returns support:
bool needs_it_support() {
bool support;

std::cout << "Hello. IT. Have you tried turning it off and on again?
Enter 1 for yes, 0 for no.\n";
std::cin >> support;

return support;
}

int main() {
// Change the following line to print the function result:
std::cout << needs_it_support();
}

Code 7/10:
#include <iostream>

// Define get_emergency_number() below:


void get_emergency_number(std::string emergency_number){
std::cout << "Dial " << emergency_number;
}

int main() {
// Original emergency services number
std::string old_emergency_number = "999";

// For nicer ambulances, faster response times


// and better-looking drivers
std::string new_emergency_number = "0118 999 881 999 119 725 3";

// Call get_emergency_number() below with


// the number you want!
get_emergency_number(new_emergency_number);
}

Code 8/10:
#include <iostream>
// Define name_x_times() below:
void name_x_times(std::string name, int x){
while(x>0){
std::cout << name;
x--;
}
}

int main() {
std::string my_name = "Add your name here!";
int some_number = 5; // Change this if you like!
// Call name_x_times() below with my_name and some_number
name_x_times("adfs\n",6);
}

Code Challenge: C++ Functions


Code 2/7:
#include <iostream>
// Define introduction() here:
void introduction(std::string first_name, std::string last_name){
std::cout << last_name << ", " << first_name << " " << last_name;
}

int main() {
introduction("Beyonce", "Knowles");
}

Code 3/7:
#include <iostream>

// Define average() here:


double average(double num1, double num2){
return (num1+num2) / 2;
}

int main() {
std::cout << average(42.0, 24.0) << "\n";
std::cout << average(1.0, 2.0) << "\n";
}

Code 4/7:
#include <iostream>
#include <cmath>

// Define tenth_power() here:


int tenth_power(int num){
return pow(num,10);
}

int main() {
std::cout << tenth_power(0) << "\n";
std::cout << tenth_power(1) << "\n";
std::cout << tenth_power(2) << "\n";
}

Code 5/7:
#include <iostream>
#include <vector>
// Define first_three_multiples() here:
std::vector<int> first_three_multiples(int num){
std::vector<int> multiples;
for(int i = 1; i < 4; i++){
multiples.push_back(num*i);
}
return multiples;
}

int main() {
for (int element : first_three_multiples(8)) {
std::cout << element << "\n";
}
}

Code 6/7:
#include <iostream>

// Define needs_water() here:


std::string needs_water(int days, bool is_succulent){
if (!is_succulent && days>3){
return "Time to water the plant.";
} else if (is_succulent && days <= 12){
"Don't water the plant!";
} else if (is_succulent && days>=13){
return "Go ahead and give the plant a little water.";
} else {
return "Don't water the plant!";
}
}

int main() {
std::cout << needs_water(10, false) << "\n";
}

Code 7/7:
#include <iostream>
#include <algorithm>
// Define is_palindrome() here:
bool is_palindrome(std::string text){
std::string textReversed = text; // create clone of text to reverse
// using inbuilt reverse function to reverse the order of elements in
any container
reverse(textReversed.begin(), textReversed.end());
if (text == textReversed){
return true;
} else {
return false;
}
}

int main() {
std::cout << is_palindrome("madam") << "\n";
std::cout << is_palindrome("ada") << "\n";
std::cout << is_palindrome("lovelace") << "\n";
}

Functions: Scope & Flexibility


Code 1/9:
#include <iostream>
void enter_code(int passcode) {
std::string secret_knowledge = "https://s3.amazonaws.com/codecademy-
content/courses/regex/onyourexcitingjourneylearningtocodeyouwillfindthis
.gif";

if (passcode == 0310) {
std::cout << secret_knowledge << "\n";
} else {
std::cout << "Sorry, incorrect!\n";
}
}

int main() {
enter_code(0310);
}

Code 2/9:
#include <iostream>
#include <cmath>

// Add declarations here:


double average(double num1, double num2);
int tenth_power(int num);
bool is_palindrome(std::string text);

int main() {
std::cout << is_palindrome("racecar") << "\n";
std::cout << tenth_power(3) << "\n";
std::cout << average(8.0, 19.0) << "\n";
}

#include <iostream>
#include <cmath>

// Add definitions here:


double average(double num1, double num2) {
return (num1 + num2) / 2;
}

int tenth_power(int num) {


return pow(num, 10);
}

bool is_palindrome(std::string text) {


std::string reversed_text = "";

for (int i = text.size() - 1; i >= 0; i--) {


reversed_text += text[i];
}

if (reversed_text == text) {
return true;
}

return false;
}

Code 3/9:
#include <iostream>
#include "fns.hpp"

int main() {
std::cout << is_palindrome("noon") << "\n";
std::cout << tenth_power(4) << "\n";
std::cout << average(4.0, 7.0) << "\n";
}

// Move function declarations here:


double average(double num1, double num2);
int tenth_power(int num);
bool is_palindrome(std::string text);

#include <iostream>
#include <cmath>

double average(double num1, double num2) {


return (num1 + num2) / 2;
}

int tenth_power(int num) {


return pow(num, 10);
}

bool is_palindrome(std::string text) {


std::string reversed_text = "";

for (int i = text.size() - 1; i >= 0; i--) {


reversed_text += text[i];
}

if (reversed_text == text) {
return true;
}

return false;
}

An inline function is a function definition, usually in a header file, qualified by inline. It can help (or
hinder) execution speed by advising the compiler to insert the functions body where the function
call is. You should always use the inline keyword if you are inlining functions in a header, except
for member functions (single line functions that are very short).
Code 4/9:
#include <iostream>
#include <chrono>

#include "night.hpp"

int main() {
// Measure time taken for goodnight1():
std::chrono::high_resolution_clock::time_point start =
std::chrono::high_resolution_clock::now();

std::cout << goodnight1("tulip");

std::chrono::high_resolution_clock::time_point end =
std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> time_span = end - start;

// Print time taken for goodnight1():


std::cout << "Time taken for goodnight1(): " << time_span.count() << "
milliseconds.\n\n";

std::cout << goodnight2("eraser", "ivy");


}

inline
std::string goodnight1(std::string thing1) {
return "Goodnight, " + thing1 + ".\n";
}
std::string goodnight2(std::string thing1, std::string thing2);

#include <string>

std::string goodnight1(std::string thing1) {


return "Goodnight, " + thing1 + ".\n";
}

std::string goodnight2(std::string thing1, std::string thing2) {


return "Goodnight, " + thing1 + " jumping over the " + thing2 + ".\n";
}

Code 5/9:
#include <iostream>
#include "coffee.hpp"

int main() {
// coffee black
std::cout << make_coffee();

// coffee with milk


std::cout << make_coffee(true);

// coffee with milk and sugar


std::cout << make_coffee(true, true);

// coffee with sugar


std::cout << make_coffee(false, true);
}

std::string make_coffee(bool milk=false, bool sugar=false);

#include <string>

std::string make_coffee(bool milk, bool sugar) {


std::string coffee = "Here's your coffee";
if (milk and sugar) {
coffee += " with milk and sugar";
} else if (milk) {
coffee += " with milk";
} else if (sugar) {
coffee += " with sugar";
}
return coffee + ".\n";
}

Overloading
Code 6/9:
#include <iostream>
#include "num_ops.hpp"
int main() {
std::cout << fancy_number(12, 3) << "\n";
std::cout << fancy_number(12, 3, 19) << "\n";
std::cout << fancy_number(13.5, 3.8) << "\n";
}

int fancy_number(int num1, int num2);


int fancy_number(int num1, int num2, int num3);
int fancy_number(double num1, double num2);

int fancy_number(int num1, int num2) {


return num1 - num2 + (num1 * num2);
}

int fancy_number(int num1, int num2, int num3) {


return num1 - num2 - num3 + (num1 * num2 * num3);
}

int fancy_number(double num1, double num2) {


return num1 - num2 + (num1 * num2);
}

A template is a C++ tool that allows programmers to add data types as parameters. Comes in
handy for classes and functions. std::string and std::vector are both template-based types.
Templates are entirely created in header files. Templates let you choose the type implementation
right when you call the function. Using templates will slow down the programs compile time, but
speed up the execution time.
Code 8/9:
#include <iostream>
#include "numbers.hpp"

int main() {
std::cout << get_smallest(100, 60) << "\n";
std::cout << get_smallest(2543.2, 3254.3) << "\n";
}

// Replace these declarations with a template


template <typename T>
T get_smallest(T num1, T num2){
return num2 < num1? num2 : num1;
}

Classes and Objects


Code 1/7:
#include <iostream>
#include "song.hpp"
int main() {

// Create the Song class below:


class Song {

};

Code 2/7:
#include <iostream>
#include "song.hpp"

int main() {

#include <string>

// add the Song class here:


class Song{
std::string title;

public:
void add_title(std::string new_title);
std::string get_title();
};

#include "song.hpp"

// add Song method definitions here:


void Song::add_title(std::string new_title){
title = new_title;
}

std::string Song::get_title(){
return title;
}
Code 3/7:
#include <iostream>
#include "song.hpp"

int main() {
Song electric_relaxation;

electric_relaxation.add_title("Electric Relaxation");

std::cout << electric_relaxation.get_title();


}

#include <string>

// add the Song class here:


class Song{
std::string title;

public:
void add_title(std::string new_title);
std::string get_title();
};

#include "song.hpp"

// add Song method definitions here:


void Song::add_title(std::string new_title){
title = new_title;
}

std::string Song::get_title(){
return title;
}

By default everything in a class is private


Code 4/7:
#include <iostream>
#include "song.hpp"
int main() {
Song electric_relaxation;
electric_relaxation.add_artist("A Tribe Called Quest");
std::cout << electric_relaxation.get_artist();
}

#include <string>

class Song {
std::string title;
std::string artist;

public:
void add_title(std::string new_title);
std::string get_title();
void add_artist(std::string new_artist);
std::string get_artist();
};

#include "song.hpp"

// add Song method definitions here:


void Song::add_title(std::string new_title) {
title = new_title;
}

std::string Song::get_title() {
return title;
}

void Song::add_artist(std::string new_artist){


artist = new_artist;
}

std::string Song::get_artist(){
return artist;
}

Code 5/7:
#include <iostream>
#include "song.hpp"

int main() {
Song back_to_black("Back to Black","Amy Winehouse");
}

#include <string>

class Song {
std::string title;
std::string artist;

public:
// Add a constructor here:
Song(std::string new_title, std::string new_artist);

std::string get_title();
std::string get_artist();
};

#include "song.hpp"

// add the Song constructor here:


Song::Song(std::string new_title, std::string new_artist)
:title(new_title), artist(new_artist){}

std::string Song::get_title() {
return title;
}

std::string Song::get_artist() {
return artist;
}

Code 6/7:
#include <iostream>
#include "song.hpp"

int main() {
Song back_to_black("Back to Black", "Amy Winehouse");
}

#include <string>

class Song {
std::string title;
std::string artist;

public:
Song(std::string new_title, std::string new_artist);
// Add a destructor here:
~Song();

std::string get_title();

std::string get_artist();
};

#include "song.hpp"
#include <iostream>

Song::Song(std::string new_title, std::string new_artist)


: title(new_title), artist(new_artist) {}

// add the Song destructor here:


Song::~Song(){
std::cout << "Goodbye Drama!\n";
}

std::string Song::get_title() {
return title;
}

std::string Song::get_artist() {
return artist;
}

References and Pointers


Pointers and References allow programmers to directly manipulate memory in order to optimize
performance. In C++, a reference variable is an alias for something else, that is, another name for
an already existing variable. Anything that happens to the reference also happens to the original,
aliases cannot be changed to alias something else.
Code 2/9:
#include <iostream>

int main() {
int soda = 99;
int &pop = soda;
pop++;
std::cout << pop << "\n";
std::cout << soda << "\n";
}

Using references as arguments allows us to modify the argument’s values. Saves computational
cost as you don’t need to make a copy of the argument.
Code 3/9:
#include <iostream>

int triple(int &i) {


i = i * 3;

return i;
}

int main() {
int num = 1;

std::cout << triple(num) << "\n";


std::cout << triple(num) << "\n";
}

The const keywords tells the compiler we won’t change something (for constants).
double const pi = 3.14;
Code 4/9:
#include <iostream>

int square(int const &i) {


return i * i;
}

int main() {
int side = 5;

std::cout << square(side) << "\n";


}

The “address of” operator, &, is used to get the memory address, the location in the memory, of an
object. A memory address is usually denoted in hexadecimal instead of binary for readability and
conciseness.
When & is used in a declaration it is a reference operator,
When & is not used in a declaration is an address operator.
Code 5/9:
#include <iostream>

int main() {
int power = 9000;

// Print power
std::cout << power << "\n";

// Print &power
std::cout << &power << "\n";
}

A pointer variable stores a memory address, pointers are an older mechanism that was inherited
from C.
Code 6/9:
#include <iostream>

int main() {
int power = 9000;

// Create pointer
int* ptr = &power;

// Print ptr
std::cout << ptr << "\n";
}

The dereference operator, *, is used to obtain the value pointed to by a variable, done by
preceding the name with *.
When * is used in a declaration, it is creating a pointer.
When * is not used in a declaration, it is a dereference operator.
Code 7/9:
#include <iostream>
int main() {
int power = 9000;

// Create pointer
int* ptr = &power;

// Print ptr
std::cout << ptr << "\n";

// Print *ptr
std::cout << *ptr << "\n";
}

When we declare a pointer, int* ptr, its content is not initialized, which is dangerous, we need
to initialize a pointer by assigning it a valid address. If we don’t know where we are pointing to we
can use a null pointer, nullptr. (nullptr is a modern replacement to NULL)
Code 8/9:
#include <iostream>

int main() {
int power = 9000;

// Create pointer
int* ptr = nullptr;

// Later in the program...


ptr = &power;

// Print ptr
std::cout << ptr << "\n";
}

Code 9/9:
#include <iostream>

int main() {
std::cout << "Dear Self,dont die lol, 03/07/2019\n";
}

Static Members

Code 1/12:

Code 2/12:
Code 3/12:

Code 4/12:

Code 5/12:

Code 6/12:

Code 7/12:

Code 8/12:

Code 9/12:

Code 10/12:

Code 11/12:

Code 12/12:

You might also like