c++ notes

some of these notes may have been created from other online sources.

they are just my home schooling notes.

 

 

const – declare unchangeable data
enum – const also
#typedef – declare alias (#typedef int myname)
#define – declare alias (#define myage 30)
all statements end with a semicolon.
use braces to create compund statements or “blocks” (multiple lines multiple instructions)
#include < iostream >
keyword static causes the variable to live throughout the whole time the program is executing

when you use the keyword static on a variable that is defined in a file outside of the main function,
it’s scope is limited to that file (.c file)

when you have multiple files and you define a variable in one file, to use it in the other file put the keyword
extern in front of the variable in the file you want to use it in. when you use the keyword extern on a variable you can not change it (the value) .

the difference between “#include “iostream” and #include <iostream> is that the first one looks in the current directory for the file,
the second looks in the directories your system uses to hold include files

the keyword “volatile” means that a variable can be modified even if the program itself does not do the modification (for example
serial port communications where it would be modified by an external source).

when you use the keyword static before the datatype for a function you are creating it limits the functions use to that file only: static int mmyfunction();

argc[]  // number of arguents to program
argv[1] // second argument to program (first is name of program) this is what you type on the command line

Unicode uses 16 bits
ASCII uses 8 bits

kill -SIGQUIT process_id   //causes core dump
(gdb) generate-core-dump

Set size for core dumps in kernel:
ulimit -c unimited

check size for kernel core dump:
ulimit -c

Set size for core dumps:
ulimit unimited

check size for score dump:
ulimit

CLR SUPPORT IN VISUAL STUDIO:
click project menu
open project properties
configuration properties
general
common language runtime support = /clr

activating the “hidden” maintenance menu for ddd:
ddd –maintenances
——————————————————————-
command line compiler = cl.exe

——————————————————————-
pointer = 4 bytes = 32bits

——————————————————————-
STRINGS:
#include <string.h>

int main ()
{
char str1[]= “To be or not to be”;
char str2[40];
char str3[40];

/* copy to sized buffer (overflow safe): */
strncpy ( str2, str1, sizeof(str2) );

/* partial copy (only 5 chars): */
strncpy ( str3, str2, 5 );
str3[5] = ‘�’;   /* null character manually added */

return 0;
}
——————————————————————-
when you have functions that take pointers or ref*a erences as arguments you must pass in the proper type.

this means:

myfunction(int * a );  //prototype for function which takes a pointer to int

would be called like so:
int b = 29;
int * a = &b;

myfunction(a); //calling the function passing a pointer as requested

inside the function:
a = memory address
*a = value at memory address

so to set the value for what a variable has rather than the memory address use * before the pointer name
int * a;
*a = 30;

——————————————————————-

right shift >> and left shift << movre an entire bit sequence right one or left one

left shift doubles the number
<<2 left //shift 2 times Quadruples the number
>> //divides the number by 2

——————————————————————-
FUNCTIONS:

int myfunction();   // function prototype

int myfunction()    //function definition
{
code here
return 0;
}

functions with default values:
int myfunction(double fun, int abc = 5); //prototype for default values

functions can call themselves
functions can be overloaded with the same name but diffrent arguments.
The prototype if not required if you define the whole function before it is used.
variables created inside the function have scope of the function itself.
when you call the function you use the real names of the variables passed in.
when you create a prototype or define a function the names of variables are what will be used inside the function.

FRIEND FUNCTIONS:
when a friend function is defined in the private area of a class it allows the friend to access that private member
keyword friend is used on the far left of the function declaration
you can also make classes friends

how to call a function that has been overridden: use the scope resolution operator
myclass myobject;

myobject.mybase::functionname();
base class name above

VIRTUAL FUNCTIONS:
virtual function tell the program to go look and see if there are any more-derived versions of the function available.
use the keyword virtual in front of the function to make it a virtual function.
when using a virtual function in the base class use a virtual destructor.
a base class that can not be instantiated is called an abstract base class.
virtual functions are managed by the VIrtual Function Table (VFT).

pure virtual functions:
class AbstractBase
{
public:
virtual void DoSomething() = 0; //pure virtual function
};

tell the compiler that it needs to be implemented by the derived class.

when you have a hierarchy of classes that inherit from each other it is possible to use the keyword virtual
when declaring the inheritance list so that when there is duplicate members it chooses the correct one for the class you are in

class myclass: public virtual baseclass

VFT = the virtual function table is part of a base class hidden in memory (an address which is 4 bytes (32bit) is hidden
on the end of the base class in memory). the address points to a table of functions.

——————————————————————-
LOOPS:
if (x==2)
x++;
else
x–;

if statements can be nested.

if (x==2)
{
if(x==3)
{x++;}
}

use the braces with loops to include multiple lines of code “{}”

GOTO LOOPS:
mylabel:
some code
goto mylabel; //execution jumps to “mylabel:”

WHILE LOOPS:

while (x<31)
{
x++
}

the do while loop is close to the above

do
{
x++;
}
while(x<20)

FOR LOOPS:

for(x=0;x<8;x++)
{
some code
}

INFINITE LOOPS:
while(1)
{
x++;
}

do
{
x++;
}
while(1)

for(;;)
{
x++
}

to get out of a loops (like the infinite ones above use “break” (usually with an if statement)

——————————————————————-

——————————————————————-

System::Console::WriteLine(“Hello C++/CLI World”)
std::cout << “hello” << std::endl;
std::cin >> test; //reads input from keyboard until whitespace(input will end upon whitespace char) and enter key
std::cin >> test1, test2;  //reads two enter keys. first text entered then enter key, then second text and enter key
——————————————————————-
the difference between xor and or is that when both variables are true or false the xor = false
^ = xor
! = not
| = or
& = and

|| = or  // one of the test conditionals but be true
&& = and // both conditionals must be true
——————————————————————-
CLASSES:
Any program that uses an object of a particular class can access the public portions directly.
A program can access the private members of an object only by using the public member functions or by being friend functions.
By making a function a friend to a class, you allow the function the same access privileges that a member function of the class has.
With private inheritance, public and protected members of the base class become private members of the derived class
This means the methods of the base class do not become part of the public interface of the derived object.
They can be used, however, inside the member functions of the derived class.
when you use (class myclass:public mynewclass) it will inherit all the public members of the class.
when you use (class myclass:protected mynewclass) you will inherit the public and protected members of the class (myclass)
when you use (class myclass:private mynewclass) you will inherit the public and protected members of the class (myclass)
when you use protected no one can access the protected members without inheriting them using private or protected.
by deafult the members of a class are private where as in a struct they are public
the functions and variables you define in a class cannot be accessed without the scope resolution operators.

how to inherit multiple classes: class myclass:public classone, public class2
just use a comma

class myclass
{
private:
code here is private to other classes and functions outside of this class.

protected:
code here becomes private in derived classes using private inheritance

public:
myclass(const myclass& newname);            //copy constructor declaration
code here is accessable by anyone
code here becomes private in derived classes using private inheritance
code here is inherited by classes using public inheritance.
int testfunction();                        //testfunction prototype
myclass(int myint = 30);                   //constructor with default value
:Name(InputName), Age(InputAge)    //constructor initialization list Name, and Age are defined.
~myclass();                                //destructor
}; //notice the semicolon after the closing bracket.

myclass::myclass(const myclass& newname)   //definition of copy constructor
{
copy constructor code here;
}

myclass::testfunction()
{
code here
return 0;
}

myclass::myclass()  //constructor
{
code here //notice no return value
}

myclass instance_of_my_class; //creation of myclass object

instance_of_my_class.myfunction();  //calls myfunction stored in class instance_of_my_class

instance_of_my_class.testfunction(); //calling of function which is public
you use the dot operator if the class is not in the heap.
if it is located in the heap you use the -> operator.
instance_of_my_class->testfunction();

allocating classes on the heap:
myclass * mynewclass = new myclass;
mynewclass->testfunction();  // access public testfunction() in class object mynewclass

constructors:
constructors are functions that are called before an object is created, and before it is destroyed
they have the same name as the class itself
you can also overload the contructor. same function name, different arguments.
to call a constructor like a function when creating an object from a class:

Class   Object name  string passed to constructor.
myclass myobject    (“mystring”);

you can set the defualt values for a constructor also.

the copy constructor:
there are 2 types of object copy. deep and shallow copy.
shallow copy is when you copy the pointers to the memory and not what it points to in memory.
so in the shallow copy the data is stored at the same location.
deepcopy is when you copy what is in memory and allocate new space for the data.
the copy constructor is an overloaded constructor.
it overloads the defualt by taking a reference of the class itself.
to make a copy constructor perform a deep copy allocate space for the new variables
and assign them to the space.
for strings use strcpy();
a good time to use a copy constructor is when your class uses pointers.
to make the class so that no one can copy it make the copy constructor private:.

class A
{
public:
int x;
protected:
int y;
private:
int z;
};

class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};

class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};

class D : private A
{
// x is private
// y is private
// z is not accessible from D
};

——————————————————————-
The this pointer:
*this   //reffers to the object as a whole
this->myfunction();   /calls myfunction stored in this object

——————————————————————-
variables:

int x = 200, y = 200, z = 200;

bool b = 0;       // false
bool b = 1;       // true

bool c = true;    // obviously true
bool d = false;   // obviously false

Int64   z = 0xFEDCBA9876543210; // Hex literal assigned
float w = 123.456f;   // standard decimal notation

int a = 4; //variable initialized
int a; //variable uninitialized
char letter(‘A’);
char letter = 65; // Equivalent to A ASCII

Char  a = L’A’;       // character literal ‘A’
Char  b = L’x0041′;  // hex notation for hex 41 which happens to be ‘A’

REFERENCES:
pass a variable by reference:
you can create references of references.
put an & before the name of the variable.
a reference is simply a variable with another name which points to the same memory location as the original.

int myfunction(int & myvariable)

int rats;
int & rodents = rats; // make rodents a reference to rats reference is read only.
const int &myreference = variable;

a const reference makes it so that it can only point to that variable, and the data is unchangeable

unsigned long mileage = 0UL;
U = unsigned
L = long

explicit type coversion:
strips_per_roll = static_cast < int > (rollLength / height); // cast to int explicitly

increment operator:
++myVariable //first increment the value of the variable and then use the incremented value in the expression //prefix
myVariable++ //incremented only after its value has been used in context  //postfix

——————————————————————-
KEYWORD STATIC:
when the keyword static is used on a variable in a class it is shared acrost all instances of that class
when you use the keyword static on a variable in a function it retains its value even when the function is done.
every time you call the function it will still have the last value that was set

——————————————————————-
POINTERS:
pointers are variables that store memory addresses (you can get the memory address of a variable by using the & infront of it)
you create a pointer like so:
int * mypointer = NULL;
mypointer = &avariable; //initialize the pointer

or init on creation:
int * mypointer = &myvariable;

when you place an * infront of a pointer it gives you the value of the pointer ( the value in memory, not the memory address)
when you use a pointer (say with std::cout) and you just use the name of the pointer it will output the memory address, not the value stored there

when you increment a pointer it increments to the next space of that type
so if it is a byte it will be the next byte.

when you use const on a pointer it make it point only to what it was initialy pointing to
int * const mypointer = &variable;  // note it must be initialized when created.

when you mark the pointer const before the type definition it makes the data it points to const. unchangeable data.
const * mypointer = &variable; //pointer can point to other variables but the data stored there can not change
mypointer = &another_variable; //ok

const pointer with const data(both the pointer and the data are const):
const * const mypointer = &dataname;

——————————————————————-
HEAP ALLOCATION USING NEW:
note that when using new you specify the size of the array after new not the variable name.
it takes a pointer to store the memory address returned by new.

int * myint = new int[5]; //allocate array with 5 buckets
*myint = 1,2,3,4,5;  // initialize 5 buckets of array

when finished using the pointer call delete on it:
delete [] myint;  //notice when you delete an array you put the brackets before the name of the variable.

if you do not have an array you do not use the brackets:
int * myint = new int;
delete myint; //regular delete of pointer.

the new version of “new” has an option called “nothrow” which returns NULL if a call to new does not allocate
the proper storage. This makes it possible to test if pointer == NULL.
If the pointer is null you know new did not complete.

——————————————————————-

ARRAYS:
arrayname is actually a pointer to element[0]. The Zero Bucket.

array – int myarray[5] = {11,12,13,14,15};  //initializer list
int myarray[5];

int myarray[] = {30,30,30}; // initialize an array with 3 buckets

myarray[3] = 123;  // 4th bucket in array being set

multi dimensional arrays can be initialized by:
int myarray[3][3]= {{3,3,3,3,3,3}};
notice the comma and second brace

so there is 2 braces on each side and a  semicolon on the end

——————————————————————-
TENARY OPERATOR:
(expression evaluated to bool) ? first : second
if expression is true first is used, otherwise second is used

——————————————————————-
STRINGS:
You need to remember to save one bucket for the null terminator.

char cat[5] = {91f92, 91a92, 91t92, 91s92, 91�92}; // the null terminator is manually added
char bird[10] = 93Mr. Cheep94; // the null terminator is automatically added
char fish[] = 93Bubbles94;     // the null terminator is automatically added

cstyle strings: char * mystring = “m-audio”;

——————————————————————-
enum myenum
{
grey = 2,
yellow = 4,
green = 7,
};     //notice the semicolon at the end

——————————————————————-

switch (expression)
{
case Label:
label++;
break;

case noLabel:
case noLabel2:   //switch statements can check more than one at a time
label–;
break;

default:
label–;
break;
}

enum Week {Mon = 1, Tues, Wed, Thurs, Fri, Sat, Sun} thisWeek;
thisweek creates the instance of enumeration type Week
Mon = 1 assigns the value 1 to Mon, normally all enum values start counting from 0 on up. so Tues would be 2
enumerators to not need to have unique values so Tues could also be 1 by assigning it Tues = 1

enumerators can be any character such as below
enum Punctuation {Comma = ‘,’, Exclamation = ‘!’, Question = ‘?’} things;
——————————————————————-
strings are arrays of characters
char mystring[] = {‘h’,’e’,’l’,’l’,’o’
——————————————————————-

friends can invoke private data member functions and access private data members.
you can have friend functions, classes, and member functions (functions in a class)

example friend function:

// friend functions
#include <iostream>
using namespace std;

class Rectangle {
int width, height;
public:
Rectangle() {}
Rectangle (int x, int y) : width(x), height(y) {}
int area() {return width * height;}
friend Rectangle duplicate (const Rectangle&);   //the friend function declared inside this class it will have access to the private data memebers and functions
};

Rectangle duplicate (const Rectangle& param)
{
Rectangle res;
res.width = param.width*2;
res.height = param.height*2;
return res;
}

and example of a friend class:
// friend class
#include <iostream>
using namespace std;

class Square;

class Rectangle {
int width, height;
public:
int area ()
{return (width * height);}
void convert (Square a);
};

class Square {
friend class Rectangle;   // declares the friend class, this class will have access to the private members of this class
private:
int side;
public:
Square (int a) : side(a) {}
};

——————————————————————-
function templates:
you create a type which allows you to use many types with it. so you have the variable typename in the declaration and definition, then when you
call it you use an actual type name like int or char.

template <typename Any>   //any is the name of the variable type you created
void myfunction(Any &a, Any &b)
{

Any temp;   // new variable typename used to create variable called temp.
temp = a;
b = temp;
}

int abc = 2;
int def = 3;
myfunction(abc, def);

//try another type with it:
double g = 3.12;
int h = 4;
myfunction(g, h);

when you are using multiple types and you would like a specific type to be handled differently than another you can do the following:
Say you have a template which creates typename Any. Then you are going to use a type of double for one, and int for another.
you can treat the double differently than the int by doing the following:
template <typename Any>
void myfunction(Any a);
void myfunction(double & a);

then later define the function to do different stuff (the above was the prototype).

void myfunction(Any a)
{
Do something different
}

void myfunction(double & a)
{
Do stuff….
}

another way of doing it is:

template <typename Any>
void myfunction(Any a);
void myfunction<double>(double & a);

then later define the function to do different stuff (the above was the prototype).

void myfunction(Any a)
{
Do something different
}

void myfunction<double>(double & a)
{
Do stuff….
}

yet another way of doing it is:

template <typename Any>
void myfunction(Any a);
template <> void myfunction<double>(double & a);

then later define the function to do different stuff (the above was the prototype).

void myfunction(Any a)
{
Do something different
}

template <> void myfunction<double>(double & a)
{
Do stuff….
}
————————————————————————————————————————————–
Namespaces:
Namespaces are containers which encapsulate the variables, and function within.

use the namespace keyword as follows:

namespace casey {
int one;
int myfunction();
double test;
struct jjj {stuff};
}

casey::myfunction();

casey::one = 1;

to make it so you do not have to type the namespace name each time you can set the current namespace with the keyword “using”
using casey;
myfunction();

you can also nest namespaces.
using namespaceone::two::three;
function_from_three();
————————————————————————————————————————————–
Operator overloading:

without being part of the class:

Time operator+(const Time& lhs, const Time& rhs)
{
Time temp = lhs;
temp.seconds += rhs.seconds;
temp.minutes += temp.seconds / 60;
temp.seconds %= 60;
temp.minutes += rhs.minutes;
temp.hours += temp.minutes / 60;
temp.minutes %= 60;
temp.hours += rhs.hours;
return temp;
}

with being part of the class. the left hand side variable is passed as a this argument invisibly:

Time Time::operator+(const Time& rhs) const /* const means that ‘this’ is not to be modified */
{
Time temp = *this;  /* Copy ‘this’ which is not to be modified */
temp.seconds += rhs.seconds;
temp.minutes += temp.seconds / 60;
temp.seconds %= 60;
temp.minutes += rhs.minutes;
temp.hours += temp.minutes / 60;
temp.minutes %= 60;
temp.hours += rhs.hours;
return temp;
}

————————————————————————————————————————————–

page 52 – list of keywords you can not use
page 678 has all the c++ keywords
page 100 table of precedence of operators
page 182 const pointers

compound assignment operators on page 96
bitwise operators on page 92
operator precedence page 99-100
BODMAS = brackets orders division multiplication subtraction

Leave a Reply