C++ Tutorial
=========================================================
//test001.cpp
#include <iostream>
main() {
std::cout<<"Hello" << std::endl;
}
=========================================================
To compile and run on unux: c++ or CC (not cc or gcc)
which c++
c++ -o a test001.cpp
./a
hello
On Windows - several free compilers available, for example from borland.com:
bcc32.exe hello.cpp ... hello.exe Hello
There also Microsoft compilers (MS Visual C++, C++.NET).
You can also install cygwin (from RedHat) and use gcc.
=========================================================
//test002.cpp
//use "using namespace ..." to avoid typing it every time
#include <iostream>
using namespace std;
main() {
cout<<"Hello" << endl;
}
=========================================================
You can mix C and C++ libraries in one program:
#include <iostream>
#include <stdio.h>
using namespace std;
main()
{
cout<<"Hello C++"<<endl;
printf("Hello C printf\n");
}
=========================================================
//test003.cpp
#include <iostream>
using namespace std;
#define MAMA "mama" << endl;
main() {
cout << MAMA
}
=========================================================
// test004.cpp
#include
using namespace std;
const int ii = 5; // const will not allow to change it
int main() {
int n;
cout<<"Hello" << ii << "Dear"
"Friend" << endl;
cout<<"Please\nPlease enter a number: ";
cin>> n;
cout<<"You entered: "<< n <<endl;
cout<<"Squared: "<< n*n <<endl;
return 0;
}
=========================================================
C++ inherits all standard operators from C, for example:
++a; a++; a += 2; a -= 2; a *= 4; a *= 5;
=========================================================
data types:
int, char, long int, float, double, long double, bool - boolean (2 values: true and false - same as 1 and 0) cout << sizeof (char); // to show the size in memory
unsigned modifier: unsigned int, …
sizeof():
// test005.cpp
#include <iostream>
using namespace std;
main() {
cout << "sizeof(int) : " << sizeof(int) << endl;
cout << "sizeof(char) : " << sizeof(char) << endl;
cout << "sizeof(long) : " << sizeof(long) << endl;
cout << "sizeof(float) : " << sizeof(float) << endl;
cout << "sizeof(double) : " << sizeof(double) << endl;
cout << "sizeof(long double) : " << sizeof(long double) << endl;
}
==
Running this program on a linux box: $ c++ -o a test005.cpp $ ./a sizeof(int) : 4 sizeof(char) : 1 sizeof(long) : 4 sizeof(float) : 4 sizeof(double) : 8 sizeof(long double) : 12
Enumerated types:
enum weekDay {Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday};
// Monday will be 2, Tuesday - 3, etc.
weekDay myDay = Monday;
// ...
if (myDay != Sunday && myDay != Saturday)
myDay = Saturday;
Define your own types using the "typedef" statement:
typedef int weekDays[7];
main() {
weekDays theDays; // array of 7 elements
// ...
}
Type casting:
// test006.cpp
#include <iostream>
using namespace std;
int main() {
cout<<(char)65<<endl;
// The (char) is a typecast, telling the computer to
// interpret the 65 as a character, not as a number.
// It is going to give the ASCII output of the
// equivalent of the number 65
// (It should be the letter A).
return 0;
}
==
// test007.cpp
#include <iostream>
using namespace std;
//Typing ASCII character set (0..255)
int main() {
for(int x=0; x<256; x++) {
cout<<x<<". "<<(char)x<<" ";
if(x%12 == 11) cout << "\n";
}
return 0;
}
Two forms of typecasting:
char cc='A'; int i1 = (int) cc; int i2 = int(cc);
=========================================================
pointers and references:
pointers
//test008.cpp
#include <iostream>
using namespace std;
int main() {
int x; //A normal integer
int *p; //A pointer to an integer
p = &x; //pointer equals the address of x
cin>>x; //Reads in x
cout<<*p;
//Note the use of the * to
// output the actual number stored in x
return 0;
}
Three ways:
int* a; int *a; int * a;
Reference = alias (shortcut)
int A = 0;
int & rA = A; // rA is reference
// and we initialized it to be an alias for A
rA = 1; // now rA == 1, which means that A == 1 too.
A=2; // now rA == 2 too
int * prA = &rA; // &rA is same as &A
(*prA)++; // same as A++ or rA++, now they are == 3
int & rrA = rA; // one more alias for A
rrA++; // now they all == 4
const int & crA = A; // one more alias
A++; // now they all == 5
// (even crA !! But you can't do crA++;)
Pointers to functions:
void ff(int a, char b); // function itself
void (*ptf)(int a, char b); // pointer to a function
void (*afp[10])(int a, char b); // array of func. pointers
// initializing the pointer and invoking the function
ptf = ff;
(*ptf)(5,'A');
// same for the array of pointers to functions:
afp[3] = ff;
(*atf)(5,'A');
Far pointers:
int* _far pnum1 = %num1; // windows
Pointers to objects:
class myClass {
// some definitions here
}
myClass obj1; // object of the type of this class
myClass pobj1 = &obj1; // pointer to this object
pobj1->myfunc(1,2); // calling a method
Pointers to pointers:
int** pp;
=========================================================
Structures
#include <iostream.h>
using namespace std;
// define structure type
struct xampl {
char Name[21];
int Height;
};
int main() {
xampl structure = {12,"Kolya"}; // initialize the structure of type "xampl"
xampl *ptr;
structure.Height=12; // another way to initialize
structure.Name="Kolya"; // another way to initialize
ptr=&structure; // pointer to the structure
cout<<ptr->Name << " - " << ptr->Height; // note the -> notation
return 0;
}
In C++ you can copy structured variables by assigning them (or passing/returning them into/from a function).
If A,B - structures, and you do one of those:
A = B
*pA = *pB
Then actual shallow copying of a structure members will happen
(shallow means that targets of pointer members will not be followed and copied).
Same shallow copying will happen if we pass the structure to a function.
All this is demonstrated in the text below
(it is written in C-style and works in both C and C++) :
#include <stdio.h>
struct TT { int a; int b; };
struct TT A,B, *pA, *pB;
void showA(void) { printf(" A.a=%d A.b=%d\n",A.a,A.b); }
void showB(void) { printf(" B.a=%d B.b=%d\n",B.a,B.b); }
void val(struct TT s) {
s.a=5; s.b=6;
printf("inside function\n s.a=%d s.b=%d\n",s.a,s.b);
}
void pt(struct TT *s) {
(*s).a=5; (*s).b=6;
printf("inside function\n (*s).a=%d (*s).b=%d\n",(*s).a,(*s).b);
}
main () {
A.a=1, A.b=2; B.a=0, B.b=0; pA = &A, pB = &B;
printf("\n");
printf("initially:\n"); showA(); showB();
printf("B=A:\n"); B = A; showB();
printf("reset B:\n"); B.a = 0; B.b = 0; showA(); showB();
printf("*pB=*pA:\n"); *pB = *pA; showB();
printf("reset B:\n"); B.a = 0; B.b = 0; showA(); showB();
printf("\npassing struct into a function makes a shallow copy\n");
printf(" val(B)\n"); val(B); printf("outside function\n"); showB();
printf("\npassing struct into a function by pointer\n");
printf(" pt(∓B)\n"); pt(&B); printf("outside function\n"); showB();
printf("\n");
}
Output:
initially:
A.a=1 A.b=2
B.a=0 B.b=0
B=A:
B.a=1 B.b=2
reset B:
A.a=1 A.b=2
B.a=0 B.b=0
*pB=*pA:
B.a=1 B.b=2
reset B:
A.a=1 A.b=2
B.a=0 B.b=0
passing struct into a function makes a shallow copy
val(B)
inside function
s.a=5 s.b=6
outside function
B.a=0 B.b=0
passing struct into a function by pointer
pt(&B)
inside function
(*s).a=5 (*s).b=6
outside function
B.a=5 B.b=6
=========================================================
Arrays
#include <iostream.h>
int main() {
int ia[3] = { 3,4,5 }; // initialize array
cout << sizeof ia << "/" << sizeof ia[0] << "="
<< sizeof ia / sizeof ia[0] << endl;
int grid[3][3] = { { 1,2,3 }, { 1,2,3 }, { 1,2,3 } }; // initialize 2-dim array
int x, y, anarray[8][8];//declares an array like a chessboard
for(x=0; x<8; x++) {
for(y=0; y<8; y++) {
anarray[x][y]=0;
}
}
for(x=0; x<8;x++) {
for(y=0; y<8; y++) {
cout<<"anarray["<<x<<"]["<<y<<"]="<<anarray[x][y]<<" ";//you'll see
}
}
return 0;
}
=========================================================
*a + 1; // take value at addr. pointed by a - and increase the value by 1
*(a+1); // shift the address by the size of one data element (2 bytes for int) - and take the value there.
#include <iostream.h>
int arr[4] = {1,2,3,4};
int *pp;
main () {
pp = arr;
cout << "Hello" << endl;
cout << "arr[2] = " << arr[2] << " = " << *(pp+2)
<< " = " << *(arr+2) << endl;
cout << sizeof(arr)/sizeof(arr[0]);
cout << endl;
}
One thing that arrays don't require that other variables do, is a reference operator.
Example: a pointer to the string : char *ptr;
char str[40]; ptr=str; //gives the memory address without a reference operator(&) //As opposed to int *ptr; int num; ptr=#//Requires & to give the memory address to the ptr
Dynamic arrays:
create and destroy using new and delete [] operators:
#include
#include <stdio.h> // to use printf( )
void main(void) {
int *parr = new int[10];
for (int ii=0;ii<10;ii++) parr[ii]=ii*ii;
for (int ii=0;ii<10;ii++) printf("%d - %d\n",ii,parr[ii]);
delete [] parr;
}
=========================================================
=========================================================
=========================================================
=========================================================
=========================================================
