C++
Topics to Review- Virtual functions
- extern keyword
- Declaration vs definition and the use of extern
- Standard Container class and vectors
- Variable argument list (...): Better alternative in C++
- Creating your own libraries
- Recursion
- Delete a character from a string. using pointers
- Macros (P.P 191 volume 1)
- shift operator
- shifting operators
//Structures C++
#include <iostream>
#include<conio.h>
typedef unsigned short int usi;
using namespace std;
int main() {
//create struct1
struct struct1{
int i;
float k;
double o;
};
//instantiate struct1
struct1 s1, s2;
//create a pointer to point to s1
struct1* s1p=&s1;
//access the element of s1 via the pointer using the -> operator
s1p->i=44;
cout<<s1p->i<<endl;
//change the address to which s1p points. Now it points to the address of s2
s1p=&s2;
s1p->i=33;//this is equal to s1.i=33;
cout<<s2.i<<endl;
getche();
}
structures C++
//structures in C++
#include <iostream>
#include<conio.h>
typedef unsigned short int usi;
using namespace std;
int main() {
struct struct1{
int i;
float k;
double o;
};
struct1 s1, s2;
s1.i=5;
cout<<s1.i;
getche();
}
structures C++
typedef c++
typedef unsigned short int usi;
typedef
Non static variables c++
//non-static local variables c++
#include <iostream>
#include<conio.h>
using namespace std;
void function1(){
int i=0;//the variable will not preserve its value throught the program run
i++;
cout<<i<<endl;
}
int main() {
for (int k=0;k<10;k++){
function1();
}
getche();
}
static variable c++
in c++, every time you call a function, the function local variables are reinitialized. Once the function is called, the local variables are destroyed. To prevent that and to make the value of the local variable extant throughout the program life, use the static keyword.
//static local variables c++
#include <iostream>
#include<conio.h>
using namespace std;
void function1(){
static int i=0;//the variable will preserve its value throught the program run
i++;
cout<<i<<endl;
}
int main() {
for (int k=0;k<10;k++){
function1();
}
getche();
}
static variables c++
Void Pointer C++
-A void pointer can take the address of any data type
for exmple:
int i=5;
float k=9;
void* ip=&i;
void* kp=&k;
-You cannot dereference a void pointer unless you must cast back before dereferencing
*ip=3;//illegal
*(int*(ip))=3; //that's ok :)
-Void pointers are discouraged unless in very special cases.
void pointers c++
//pass by reference c++
#include <iostream>
#include<conio.h>
using namespace std;
void function1(int& z){//int& z means that function1() receives the address of the passed variable
cout<<"Indide the function before change i= "<<z<<endl;
z=6;//change the value that z reference holds. ie., i
cout<<"Inside Function after change i= "<<z<<endl;
cout<<"The address of i inside the function= "<<(long)&z<<endl;
}
int main() {
int i=5;
cout<<"Before Calling function i= "<<i<<endl;
function1(i); //it look like pass by value but it's not
//look at function1() definition
cout<<"After Calling function i= "<<i<<endl;
cout<<"The address of i in main function= "<<(long)&i<<endl;
getche();
}
pass by reference in c++, pointers
//c++ call by address
//pass by address c++
#include <iostream>
#include<conio.h>
using namespace std;
void function1(int* z){
*z=6;
cout<<"Inside Function i= "<<*z<<endl;
}
int main() {
int i=5;
int* ip=&i;
cout<<"Before Calling function i= "<<i<<endl;
function1(ip);
cout<<"After Calling function i= "<<i<<endl;
getche();
}
pass by address, pointers C++
//Call by Value C++
#include <iostream>
#include<conio.h>
using namespace std;
void function1(int z){
z=6;
cout<<"Inside Function i= "<<z<<endl;
}
int main() {
int i=5;
cout<<"Before Calling function i= "<<i<<endl;
function1(i);
cout<<"After Calling function i= "<<i<<endl;
getche();
}
call by value c++, pointers
//Pointers Basics C++
#include <iostream>
#include<conio.h>
using namespace std;
int main() {
int i=9;
int* ip=&i;
cout<<(long)ip<<endl;
ip++;
cout<<(long)ip<<endl;
ip--;
cout<<*ip<<endl;
*ip=10;
cout<<*ip<<endl;
cout<<(long)ip<<endl;
getche();
} ///:~
pointers C++
//undsigned short int size
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;
int main(void){
int counter=0;
for (unsigned short int i=1;;i++){
counter++;
if (i==0) {
cout<<"Maximum possible number using unsigned shortnint is ";
cout<<counter-1; break;}
}
getche();
return 0;
}
//cast double to int C++
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;
int main(void){
cout<<int(5e4);
getche();
return 0;
}
continue in C++
#include<conio.h>
#include<iostream>
#include<string>
using namespace std;
int main(void){
for (int i=0; i<=10;i++){
if (i==5)continue;
//don't cout 5
cout<<i;
}
getche();
return 0;
}
//Find number of prime integers in N range
//Adel Shehadeh
#include <iostream>
#include<conio.h>
using namespace std;
int main(){
int n=0;
bool prime=true;
int count =0;
while (n<=1){
cout<<"Enter N range [1-N]. N should be an integer > 1:"<<endl;
cin>>n;
}
for (int k=n;k>=2;k--){
prime=true;
for (int i=k;i>=2;i--){
if (k==i)
continue;
if (k%i==0)
{prime=false;}
}
if (prime==true)
count++;
}
cout<<count<<" prime Numbers in range.";
getche();
return 0;
}
//convert dec to ASCII C++
#include<conio.h>
#include<iostream>
using namespace std;
char getChar(int);
int main(){
int num=0;
cout<<"Enter number from 0 to 255"<<endl;
cin>>num;
cout<<"The ASCII char is: " <<getChar(num);
getche();
return 0;
}
char getChar(int i){
return char(i);
}
Copy file to a vector
#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>
using namespace std;
int main(){
vector<string> vector1;
ifstream input("input.txt");
string string1;
while (getline (input,string1)){
vector1.push_back(string1);
}
for (int i=0; i<vector1.size();i++){
cout<<i<<":"<<vector1[i]<<endl;
}
getche();
}
Create a vector<float>
#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>
using namespace std;
int main(){
vector<float> vector1;
float k=0;
for (int i=0;i<=25;i++){
k+=.1;
vector1.push_back(k);
cout<<vector1[i]<<endl;
}
getche();
return 0;
}
Square a vector in C++
#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>
using namespace std;
int main(){
vector<float> vector1;
float k=0;
for (int i=0;i<=25;i++){
k+=1;
vector1.push_back(k);
vector1[i]=vector1[i]*vector1[i];
}
for (int i=0;i<=25;i++){
cout<<vector1[i]<<endl;
}
getche();
return 0;
}
Count words in a file
#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>
//count whitespace seperted words in a file.
using namespace std;
int main(){
ifstream input("input.txt");
string str1;
int count=0;
while(input >> str1)
count++;
cout<<count;
getche();
}
Count the occurrences of a word in a file
#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>
//count whitespace seperted words in a file.
using namespace std;
int main(){
ifstream input("input.txt");
string str1;
int count=0;
while(input >> str1)
if (str1=="and")
count++;
cout<<count<<"times the word "and" occured";
getche();
}
Print the lines of a file but backward in C++
#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>
using namespace std;
int main(){
//print the lines of a file backward using vectors
vector<string> vector1;
ifstream in("input.txt");
string line;
while(getline(in, line))
vector1.push_back(line);
for(int i = (vector1.size()-1); i > 0 ; i--)
cout << i << ": " << vector1[i] << endl;
getche();
}
//Concatenate all the vector elements into a single string in C++
#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>
using namespace std;
int main(){
vector<string> vector1;
ifstream in("input.txt");
string line;
string finalString;
while(getline(in, line))
vector1.push_back(line);
for(int i = 0; i<vector1.size() ; i++)
finalString+=vector1[i];
cout <<finalString;
getche();
}
Copy Files using vectors
#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>
using namespace std;
int main(){
vector<string> vector1;
ifstream input("input.txt");
ofstream output("output.txt");
string string1;
while (getline (input,string1)){
vector1.push_back(string1);
}
for (int i=0; i<vector1.size();i++){
output<<vector1[i]<<endl;
}
getche();
}
copy all the words of a file to another file. Word by word
#include<conio.h>
#include<string>
#include<vector>
#include<iostream>
#include<fstream>
//copy each word in a file seperately to a vector element.
//Then copy the whole elements to another file
using namespace std;
int main(){
vector<string> wordsVector;
ifstream input("input.txt");
ofstream output("output.txt");
string str1;
while(input >> str1) //read input from file to str1. Line by line
wordsVector.push_back(str1);
for(int i = 0; i < wordsVector.size(); i++)
output << wordsVector[i] << endl;
getche();
}
C++ Copy entire file to string. Copy file to string
#include <iostream>
#include <conio.h>
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream in("in.txt");
string string1, string2;
while (getline (in,string1)){
string2+=string1+"n";
}
cout<<string2;
getche();
}
The problem with reading lines
from a file into individual string objects is that you don’t know up
front how many strings you’re going to need – you only know after
you’ve read the entire file.
c++ copy file 1 to file 2
#include <fstream>
#include <string>
using namespace std;
int main() {
ifstream in("in.txt");
ofstream out("out.txt");
string s;
int lineNumbers=0;
while (getline (in,s)){
out<<s<<"n";
lineNumbers++;
}
cout<<lineNumbers<<" Lines copied babe";
getche();
} ///:~
IS-A relationship in inheritance
A test for inheritance is to
determine whether you can state the is-a relationship about the
classes and have it make sense.
Like when you say: a circle is a shape.
access specifiers
C++ uses three explicit keywords to set the boundaries in a class:
public, private, and protected. Their use and meaning are quite
straightforward. These access specifiers determine who can use the
definitions that follow. public means the following definitions are
available to everyone. The private keyword, on the other hand,
means that no one can access those definitions except you, the
creator of the type, inside member functions of that type. private is
a brick wall between you and the client programmer. If someone
tries to access a private member, they’ll get a compile-time error.
protected acts just like private, with the exception that an
inheriting class has access to protected members, but not private
members. Inheritance will be introduced shortly.
Composition in C++
Becauseyou are composing a new class from existing classes, this concept is called composition (or more generally, aggregation). Composition is often referred to as a “has-a” relationship, as in “a car has an engine.”
Basic Input/Output
string mystr; cout << "What's your name? "; getline (cin, mystr);
Basic Input/Output
using the function getline() to get input
// cin with strings #include <iostream> #include <string> using namespace std; int main () { string mystr; cout << "What's your name? "; getline (cin, mystr); cout << "Hello " << mystr << ".n"; cout << "What is your favorite team? "; getline (cin, mystr); cout << "I like " << mystr << " too!n"; return 0; }
Operators
| Level | Operator | Description | Grouping |
|---|---|---|---|
| 1 | :: | scope | Left-to-right |
| 2 | () [] . -> ++ -- dynamic_cast static_cast reinterpret_cast const_cast typeid | postfix | Left-to-right |
| 3 | ++ -- ~ ! sizeof new delete | unary (prefix) | Right-to-left |
| * & | indirection and reference (pointers) | ||
| + - | unary sign operator | ||
| 4 | (type) | type casting | Right-to-left |
| 5 | .* ->* | pointer-to-member | Left-to-right |
| 6 | * / % | multiplicative | Left-to-right |
| 7 | + - | additive | Left-to-right |
| 8 | << >> | shift | Left-to-right |
| 9 | < > <= >= | relational | Left-to-right |
| 10 | == != | equality | Left-to-right |
| 11 | & | bitwise AND | Left-to-right |
| 12 | ^ | bitwise XOR | Left-to-right |
| 13 | | | bitwise OR | Left-to-right |
| 14 | && | logical AND | Left-to-right |
| 15 | || | logical OR | Left-to-right |
| 16 | ?: | conditional | Right-to-left |
| 17 | = *= /= %= += -= >>= <<= &= ^= |= | assignment | Right-to-left |
| 18 | , | comma | Left-to-right |
Operators
| Example 1 | Example 2 |
|---|---|
| B=3; A=++B; // A contains 4, B contains 4 | B=3; A=B++; // A contains 3, B contains 4 |
In Example 1, B is increased before its value is copied to A. While in Example 2, the value of B is copied to A and then B is increased.
Operators
Comma operator ( , )
The comma operator (,) is used to separate two or more expressions that are included where only one expression is expected. When the set of expressions has to be evaluated for a value, only the rightmost expression is considered.For example, the following code:
a = (b=3, b+2); |
Would first assign the value 3 to b, and then assign b+2 to variable a. So, at the end, variable a would contain the value 5 while variable b would contain value 3.
Another example
#include <iostream>
#include <conio.h>
using namespace std;
int main (){
int i=0;
int j=0;
j=(i=5,i+1); //the comma operator
cout<<i<<endl;
cout<<j;
getche();
return 0;
}
Operators
Bitwise Operators ( &, |, ^, ~, <<, >> )
Bitwise operators modify variables considering the bit patterns that represent the values they store.
| operator | asm equivalent | description |
|---|---|---|
| & | AND | Bitwise AND |
| | | OR | Bitwise Inclusive OR |
| ^ | XOR | Bitwise Exclusive OR |
| ~ | NOT | Unary complement (bit inversion) |
| << | SHL | Shift Left |
| >> | SHR | Shift Right |
Constants
Defined constants (#define)
#include <iostream>
#include <conio.h>
using namespace std;
int main (){
#define PI 3.14;
cout<<PI;
getche();
return 0;
}
Constants
Declared constants (const) value cannot be chagned
const int pathwidth = 100; |
Here, pathwidth and tabulator are two typed constants. They are treated just like regular variables except that their values cannot be modified after their definition.
Constants
a = 5; |
the 5 in this piece of code was a literal constant.
Variables. Data Types.
Variables. Data Types.
Variables. Data Types.
unsigned short int NumberOfSisters; |
By default, if we do not specify either signed or unsigned most compiler settings will assume the type to be signed, therefore instead of the second declaration above we could have written:
int MyAccountBalance; |
Variables. Data Types.
Constructor Initialization
The other way to initialize variables, known as constructor initialization, is done by enclosing the initial value between parentheses (()):
type identifier (initial_value) ;
For example:
int a (0); |
#include <iostream>
#include <conio.h>
using namespace std;
int main (){
int a=0; //intialization
int b(5);//constructor initialization
cout<<a<<endl;
cout<<b;
getche();
return 0;
}
Variables. Data Types.
Only letters, digits and single underscore characters are valid. In addition, variable identifiers always have to begin with a letter. They can also begin with an underline character (_ ), but in some cases these may be reserved for compiler specific keywords or external identifiers, as well as identifiers containing two successive underscore characters anywhere. In no case they can begin with a digit.
Seperate Lines
#include <iostream>
#include <conio.h>
using namespace std;
int main (){
cout<<"t"
"est"<<endl;
cout<<
"test";
getche();
return 0;
}
output:
test
test
Structure of a program
A return code of 0 for the main function is generally interpreted as the program worked as expected without any errors during its execution.
for consle programs i use the library conio.h to keep the window opened and wait for a character input
#include <iostream>
#include <conio.h>
using namespace std;
int main (){
cout<<"test"<<endl;
getche();
return 0;
}
Variables. Data Types.
Next you have a summary of the basic fundamental data types in C++, as well as the range of values that can be represented with each one:
| Name | Description | Size* | Range* |
|---|---|---|---|
| char | Character or small integer. | 1byte | signed: -128 to 127 unsigned: 0 to 255 |
| short int (short) | Short Integer. | 2bytes | signed: -32768 to 32767 unsigned: 0 to 65535 |
| int | Integer. | 4bytes | signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 |
| long int (long) | Long integer. | 4bytes | signed: -2147483648 to 2147483647 unsigned: 0 to 4294967295 |
| bool | Boolean value. It can take one of two values: true or false. | 1byte | true or false |
| float | Floating point number. | 4bytes | 3.4e +/- 38 (7 digits) |
| double | Double precision floating point number. | 8bytes | 1.7e +/- 308 (15 digits) |
| long double | Long double precision floating point number. | 8bytes | 1.7e +/- 308 (15 digits) |
| wchar_t | Wide character. | 2 or 4 bytes | 1 wide character |