If you have several *.cpp source files, all you need to do is to list them in the command, as follows: g++ -Wall -o main source1.cpp source2.cpp source3.cpp
Variables & references
Source
Output
#include<iostream>#include<string>usingnamespacestd;intmain(){intage(37);stringname("Alice Shaw");doubleconstpi(3.14159);// Constant. You can't modify it.cout<<"Hello "<<name<<". You are "<<age<<" years old."<<endl;return0;}
Hello Alice Shaw. You are 37 years old.
In C++, you can define references as follows:
Source
Output
#include<iostream>#include<string>usingnamespacestd;intmain(){intnum(16);int&refnum1(num);int&refnum2(num);stringname("Alice Shaw");string&refname(name);cout<<"Num: "<<num<<endl;cout<<"Ref Num 1: "<<refnum1<<endl;cout<<"Ref Num 2: "<<refnum2<<endl;cout<<"Name: "<<name<<endl;cout<<"Ref name: "<<refname<<endl;return0;}
$ ./main
Num: 16
Ref Num 1: 16
Ref Num 2: 16
Name: Alice Shaw
Ref name: Alice Shaw
To use a dynamic size array, first include the vector header:
#include<vector>
Then do as follows:
// Array of integers, size of 5, filled with 3vector<int>tab(5,3);// Array of strings, size of 5, filled with "hello" vector<string>tab(5,"hello");// Array of double, with no size specified and no default valuevector<double>tab;
To add and delete cells, respectively use array_name.push_back(val) and array_name.pop_back() as follows:
#include<iostream>#include<vector>#include"main.h"usingnamespacestd;intmain(){vector<vector<int>>tab;// 1st row of size 5 filled with 1tab.push_back(vector<int>(5,1));// 2nd row of size 5 filled with 2tab.push_back(vector<int>(5,2));tab[0][3]=8;tab[0][4]=9;tab[1][1]=5;tab[1][2]=4;showtab(tab);// Add 3 at the end of the 1st rowtab[0].push_back(3);showtab(tab);return0;}voidshowtab(vector<vector<int>>const&tab){unsignedintrow(0),col(0);for(row=0;row<tab.size();row++){for(col=0;col<tab[0].size();col++){cout<<" | "<<tab[row][col];}cout<<" |"<<endl;}cout<<"--------------------------"<<endl;}
#include<iostream>#include<string>#include"Garage.h"usingnamespacestd;/*** * Vehicle */Vehicle::Vehicle(intprice):m_price(price){}Vehicle::~Vehicle(){}voidVehicle::showInfo()const{cout<<"This vehicle costs $"<<m_price<<"."<<endl;}/*** * Car */Car::Car(intprice,intdoors):Vehicle(price),m_doors(doors){}Car::~Car(){}voidCar::showInfo()const{cout<<"This car has "<<m_doors<<" doors and costs $"<<m_price<<"."<<endl;}/*** * Motorcycle */Motorcycle::Motorcycle(intprice,doublespeed):Vehicle(price),m_speed(speed){}Motorcycle::~Motorcycle(){}voidMotorcycle::showInfo()const{cout<<"This motorcycle can drive "<<m_speed<<"mph and costs $"<<m_price<<"."<<endl;}
The above code produces the following output:
This car has 5 doors and costs $8550.
This motorcycle can drive 200.5mph and costs $3250.
Files
Write and Read file
Source
Output
#include<iostream>#include<fstream> /* ifstream(), ofstream() */#include<string> /* getline() */usingnamespacestd;intmain(){stringconstmyfile("test.txt");// file stream (write)ofstreammystream(myfile.c_str());if(!mystream)perror("Error creating stream");// Write to filemystream<<"This is a test file"<<endl;mystream<<"Hello world!"<<endl;// file stream (read)ifstreamreadfile(myfile.c_str());if(!readfile)perror("Error creating stream");// Read a wordstringword;readfile>>word;cout<<"A word: "<<word<<endl;// Read file line by linestringline;while(getline(readfile,line))cout<<"A line: "<<line<<endl;return0;}
$ ./main
A word: This
A line: is a test file
A line: Hello world!
Pointers
Syntax
Description
Example
&thing
Address of thing
Source
Output
#include<iostream>usingnamespacestd;intmain(){intnum(3);cout<<"Address of num: "<<&num<<endl;return0;}
#include<iostream>usingnamespacestd;intmain(){intnum1(3);// num1 set to 3int&num2(num1);// num2 as reference to num1cout<<"num1="<<num1<<", num2="<<num2<<endl;// If num1 is updated, num2 is also set to the updated valuenum1=4;cout<<"num1="<<num1<<", num2="<<num2<<endl;// If num2 is updated, num1 is also updatednum2=5;cout<<"num1="<<num1<<", num2="<<num2<<endl;// This is because both num1 and num2 point to the same addresscout<<"Addr num1="<<&num1<<", Addr. num2="<<&num2<<endl;return0;}
#include<iostream>usingnamespacestd;intmain(){intagePaul(0);int*ageAlice(0);ageAlice=newint;cout<<"How old is Paul? ";cin>>agePaul;cout<<"How old is Alice? ";cin>>*ageAlice;cout<<"Paul is "<<agePaul<<" years old and Alice is "<<*ageAlice<<" years old."<<endl;delete(ageAlice);ageAlice=0;return0;}
$ ./main
How old is Paul? 33
How old is Alice? 35
Paul is 33 years old and Alice is 35 years old.
Classes
Classes
The following program:
main.cpp
#include<iostream>#include<string>#include"Player.h"usingnamespacestd;intmain(){// Instantiation of Player classPlayerplayer1,player2("Sword",20);// Actions (methods called from Player class)player2.attack(player1);player1.drinkHealingPotion(20);player2.attack(player1);player1.attack(player2);player2.switchWeapon("Ax",40);player2.attack(player1);cout<<"=== Player 1 ==="<<endl;player1.showStatus();cout<<"=== Player 2 ==="<<endl;player2.showStatus();return0;}
Player.h
#ifndef DEF_PLAYER#define DEF_PLAYER#include<iostream>#include<string>#include"Weapon.h"classPlayer{// Methods are public so that we can call them from main()public:Player();// Default constructorPlayer(std::stringweaponName,intweaponDamage);// Constructor that overrides the default weapon~Player();// DestructorvoidsufferDamage(intdamage);voidattack(Player&target);voiddrinkHealingPotion(intpotionQuantity);voidswitchWeapon(std::stringnewWeaponName,intnewWeaponDamage);boolisAlive();voidshowStatus();// Attributes should always remain privateprivate:intm_lives;intm_mana;Weaponm_weapon;};#endif
#ifndef VEHICLE_H_#define VEHICLE_H_classVehicle{public:Vehicle(intprice);virtual~Vehicle();voidshowInfo()const;/* protected indicates that it remains private but accessible from the children */protected:intm_price;};#endif /* VEHICLE_H_ */
Vehicle.cpp
#include<iostream>#include<string>#include"Vehicle.h"usingnamespacestd;Vehicle::Vehicle(intprice):m_price(price){}Vehicle::~Vehicle(){}voidVehicle::showInfo()const{cout<<"This vehicle costs $"<<m_price<<" (call from Vehicle class)."<<endl;}
#include<iostream>#include<string>#include"Vehicle.h"#include"Car.h"usingnamespacestd;Car::Car(intprice,intdoors):Vehicle(price),m_doors(doors){}Car::~Car(){}voidCar::showInfo()const{/* Access price thanks to the protected mode in Vehicle class */cout<<"This vehicle costs $"<<m_price<<" (access m_price from Vehicle)."<<endl;cout<<"This car has "<<m_doors<<" doors (Car member)."<<endl;}
This vehicle costs $6800 (call from Vehicle class).
-----
This vehicle costs $8500 (access m_price from Vehicle).
This car has 4 doors (Car member).
-----
This vehicle costs $3850 (call from Vehicle class).
This motorcycle drives 200mph (Motorcycle member).
Below is the code for the == and != operators. The same logic can be applied for <, <=, > and >=.
main.cpp
#include<iostream>#include<string>#include"Person.h"usingnamespacestd;intmain(){Personperson1("alice",38),person2("paul",35),person3("alice",34),person4("paul",35);cout<<"Person1: ";person1.showInfo();cout<<"Person2: ";person2.showInfo();cout<<"Person3: ";person3.showInfo();cout<<"Person4: ";person4.showInfo();if(person1==person3)cout<<"Person 1 and 3 are the same"<<endl;if(person1!=person3)cout<<"Person 1 and 3 are different"<<endl;if(person2==person4)cout<<"Person 2 and 4 are the same"<<endl;if(person2!=person4)cout<<"Person 2 and 4 are different"<<endl;return0;}
#include<iostream>#include<string>#include"Person.h"usingnamespacestd;Person::Person(stringname,intage):m_name(name),m_age(age){}Person::~Person(){}voidPerson::showInfo(){cout<<m_name<<" is "<<m_age<<" years old."<<endl;}boolPerson::isIdentical(Personconst&person)const{return(m_name==person.m_name&&m_age==person.m_age);}booloperator==(Personconst&person1,Personconst&person2){returnperson1.isIdentical(person2);}booloperator!=(Personconst&person1,Personconst&person2){return!person1.isIdentical(person2);}
The above code will show the following output:
Person1: alice is 38 years old.
Person2: paul is 35 years old.
Person3: alice is 34 years old.
Person4: paul is 35 years old.
Person 1 and 3 are different
Person 2 and 4 are the same
#include<iostream>#include<string>#include<iomanip> /* for proper time format */#include"Duration.h"usingnamespacestd;Duration::Duration(inthours,intminutes,intseconds):m_hours(hours),m_minutes(minutes),m_seconds(seconds){}Duration::~Duration(){}voidDuration::showDuration(){cout<<setfill('0')<<setw(2)<<m_hours<<":"<<setfill('0')<<setw(2)<<m_minutes<<":"<<setfill('0')<<setw(2)<<m_seconds<<endl;}Duration&Duration::operator+=(constDuration&duration){intnseconds=m_hours*3600+m_minutes*60+m_seconds;nseconds+=duration.m_hours*3600+duration.m_minutes*60+duration.m_seconds;m_hours=nseconds/3600;m_minutes=nseconds%3600/60;m_seconds=nseconds%3600%60;return*this;}Duration&Duration::operator-=(constDuration&duration){intnseconds=m_hours*3600+m_minutes*60+m_seconds;nseconds-=duration.m_hours*3600+duration.m_minutes*60+duration.m_seconds;m_hours=nseconds/3600;m_minutes=nseconds%3600/60;m_seconds=nseconds%3600%60;return*this;}Durationoperator+(Durationconst&duration1,Durationconst&duration2){DurationcopyDuration1(duration1);copyDuration1+=duration2;returncopyDuration1;}Durationoperator-(Durationconst&duration1,Durationconst&duration2){DurationcopyDuration1(duration1);copyDuration1-=duration2;returncopyDuration1;}
#include<iostream>#include<string>#include<iomanip> /* for proper time format */#include"Duration.h"usingnamespacestd;Duration::Duration(inthours,intminutes,intseconds):m_hours(hours),m_minutes(minutes),m_seconds(seconds){}Duration::~Duration(){}voidDuration::showDuration(ostream&mystream)const{mystream<<setfill('0')<<setw(2)<<m_hours<<":"<<setfill('0')<<setw(2)<<m_minutes<<":"<<setfill('0')<<setw(2)<<m_seconds;}Duration&Duration::operator+=(constDuration&duration){intnseconds=m_hours*3600+m_minutes*60+m_seconds;nseconds+=duration.m_hours*3600+duration.m_minutes*60+duration.m_seconds;m_hours=nseconds/3600;m_minutes=nseconds%3600/60;m_seconds=nseconds%3600%60;return*this;}Duration&Duration::operator-=(constDuration&duration){intnseconds=m_hours*3600+m_minutes*60+m_seconds;nseconds-=duration.m_hours*3600+duration.m_minutes*60+duration.m_seconds;m_hours=nseconds/3600;m_minutes=nseconds%3600/60;m_seconds=nseconds%3600%60;return*this;}Durationoperator+(Durationconst&duration1,Durationconst&duration2){DurationcopyDuration1(duration1);copyDuration1+=duration2;returncopyDuration1;}Durationoperator-(Durationconst&duration1,Durationconst&duration2){DurationcopyDuration1(duration1);copyDuration1-=duration2;returncopyDuration1;}ostream&operator<<(ostream&mystream,Durationconst&duration){duration.showDuration(mystream);returnmystream;}