Professional Documents
Culture Documents
Index
C++ in short
Fundamentals
Clases
Objects
Bibliography
Software
Literals
Literal characters between single quoter: a, b,
Integer constants:
Decimal (0,45,) hex. (0x3f, 0x78,) octal (012, 023,)
1.2e10
1.23e-15
Examples of use:
bool a = true;
char ch = a;
bool b = false;
unsigned int num = 015;
Void
Syntactically is a fundamental type
No objects of this type exist!!!
Mainly used to:
indicate that a function does not return any value
is the basis for pointers to objects of an unknown
datatype
Enumerations (enum)
Store a set of values defined by the programmer
The range is set from 0 (if the lower value is not
negative) to the nearest power of 2 (on the right
side)
enum flag { x=1, y=2, e=8};
flag f1 = flag(5);
Pointers
A pointer store an address of another object
Also any address in memory (dangerous)
Examples:
char c = a;
Arrays
An array is a set of indexed values of same type
The index is a natural number (starting on 0)
Examples:
float f[3];
int n[2][3][4];
Declaration and initialization
char c[3] = { a, b, c };
More examples:
int v[4]= { 1, 2, 3}; // The last element will be 0
char p[] = Hello world! ; // 13 elements lenght!
Pointers to arrays
Name of array = pointer to the first element
int v[] = {1, 2, 3, 4};
int* p1=v; //pointer to the first element
int* p2=&v[0]; //pointer to first element
int* p3=&v[3]; //pointer to the last element
do_something(*p);
Constants
Consants are declared using the keyword
const.
Constants must be initialized when they are
declared
Structures
Aggregate of different dataypes, e.g.:
struct name
{
char* firstname;
char* lastname;
};
name jd = { John, Smith};
Advices
To improve code readability and maintenability:
Avoid non-trivial pointer aritmethic
Do not read or write beyond the bounds of an array
Use 0 instead of NULL
Use strings (Strings) instead of arrays of char
Avoid *void except when writing low level code
Avoid non-trivial literals
Basic I/O
C++ input and output is performed using streams
Two standard streams:
std::in
std::out
Syntax to:
send information to stream is <<
receive information from a stream is >>
char c;
std::cin >> c; //read
std::cout << c; //write
Conditionals
Statements used to create conditional constr.:
if (condition) statement
if (condition) statement else statement
switch (condition) statement
if (a<=b)
max = b;
else
max = a;
Iteration
while (condition) statement
do statement while (expression);
for (init-statement; condition; expression) statement
int i = 1;
int i = 1;
do
cout << i;
cout << i;
i++;
i++;
} while(i <= 20)
located = false;
li = 0; lj=0;
Arithmetic operators
Operator Name
Syntax
Operator Name
Syntax
Plus
+a
Assignment by
Subtraction
a -= b
Addition (Sum)
a+b
Multiplication
(Product)
a*b
Prefix increment
++a
Assignment by
Multiplication
a *= b
Postfix increment
a++
Division (Quotient)
a/b
Assignment by
Addition
a += b
Assignment by
Division
a /= b
Unary Minus
(Negation)
-a
Modulus
(Remainder)
a%b
Subtraction
(Difference)
a-b
Assignment by
Modulus
a %= b
Postfix decrement
--a
Syntax
Operator Name
Syntax
Less Than
a<b
Not Equal To
a != b
Equal To
a == b
Greater Than
a>b
Logical Negation
!a
a >= b
Logical AND
a && b
Logical OR
a || b
Bit operators
Operator Name
Syntax
Operator Name
Syntax
a << b
Assignment by
Bitwise AND
a &= b
Assignment by
Bitwise Left Shift
a <<= b
Bitwise OR
a|b
a >> b
Assignment by
Bitwise OR
a |= b
Assignment by
Bitwise Right Shift
a >>= b
Bitwise XOR
a^b
Bitwise One's
Complement
~a
Assignment by
Bitwise XOR
a ^= b
Bitwise AND
a&b
Advices
Use the standard library whenever possible
Avoid difficult expressions
Use parenthesis
Avoid difficult castings
Avoid goto
Avoid do-statement
Do not declare varibles if they dont have an initial value.
#include <stdio.h>
#include <stdlib.h>
while(div > 1)
{
det = det * (num % div);
#include <iostream>
using namespace std;
int main()
{
div--;
}
if (det == 0)
cout << "The number is not prime" << endl;
else
#include <stdio.h>
#include <stdlib.h>
int vector[T];
#include <iostream>
#define T 10
{
cout << "Insert number " << (i+1) << ":\t";
cin>>vector[i];
void order(int[]);
order(vector);
for (int m=0; m < T; m++) cout<< vector[m] << " ";
cout << endl;
system("PAUSE");
return 0;
}
vect[k+1] = a;
Functions
The declaration of a function provides:
The name of the function
The type of returned value (if any)
The number and types of arguments
On calls to functions, datatypes are checked.
Implicit castings are performed if necessary.
Functions (y2)
Every function must be declared somewhere.
A definition is a declaration that also includes the main body of
the function
On declaration is not necessary to indicate the name of the
arguments.
On definitions is not required too if arguments are not used but
just declared for compatibility issues.
Arguments can be declared inline so that the compiler
generates code and not a call to the function.
Static variables are shared for all calls to the function.
Example
extern void swap(int*, int*, char*) //declaration
void swap(int* p, int* q, char* ) //definition
{
int t = *p;
*p = *q;
*q = t;
}
inline int sum(int a, int b)
{
return a+b;
}
Arguments
Semantics of arguments is similar to their initialization
Datatypes are checked.
Implicit castings are performed if necessary
Arguments can be by value or by reference
Arguments by reference are pointers
Const can be used on arguments by reference to prevent them
from being modified
Arrays are always arguments by reference
Default values could be used on arguments
Examples
void f(int value, int& reference)
{
value++; //increment the local copy
reference++;//increment the original variable
}
void g(const int& parameter) //parameter will not be changed
Returned values
A function returns a value if it has not been
declared as void
References to local variables should not be
returned (their memory space is reassigned when
the function returns)
void f() {return i; } // Wrong!
int& g() {return local;} // Wrong!
int* h() {return &local;} // Fatal!
Function overload
Different functions can have the same name
The compiler will select the appropiate function to call
according to the deatatypes of expressions and arguments:
Exact match or with trivial conversions (e.g. a name of an array
to a pointer)
Match using promotions of similar datatypes (e.g. bool to int,
char to int, float to double)
Match using standard castings (e.g. int to double, int* to void*)
Match using user-based castings.
Returned values are not considered for overloads.
More on functions
Functions with an undetermined number of
arguments can be declared.
Pointers to functions are allowed.
They can be used to call the functions.
Macros are permitted.
They can be used for conditional compilations.
Advices
Be careful with arguments by reference that do not
use const
Avoid macros
Avoid functions with an undetermined number of
arguments
Do never return references to local variables
CLASSES
Clases
Classes are user-defined datatypes
Classes have:
propertites (attributes)
methods (actions that can perform)
constructors to initialize objects of that class (properties, )
may have static properties and/or methods that are shared by
all the instances of the class
Privacy
Classes may have
Public and private
Methods and properties
Constructors
Special method, to initialize the object
Same name that the class have
Can be overloaded
Default values can be interesting for constructors
Instead of creating multiple constructors
Static members
Classes may have static members
Static keyword is used
Static members are part of the class instead of being part
of objects (instances)
Access to static members the name of the class is used
instead of the name of the object.
Constant functions
Methods declared using const
Not allowed to modify the object (properties)
Some properties can be changed from constant functions
They are declared as mutable
Example
class Date
{
int year;
int month;
public:
void print() const;
void Date();
}
void Date::print() {}
int day;
Self-reference
Non-static methods can use the keyword this
Reference to the object
Exercices
Implement a class called Date to store dates
The constructor/s can get 3 integer arguments (day,
month, year) and can be called with 0, 1, 2 or 3
arguments. Not present arguments shall be replaced by
default arguments. Default date must be common and
shall not be modified.
Include functions to update and get the different elements
of the date (day, month, year)
Create a function to decide whether a date is more recent
than other (both dates can be arguments)
Exercices
Implement a class called Person with information about
people. Include
Constructor/s with 3 arguments (FirstName,
LastName y Birthday), that can be called using 2 or
3 arguments (if birthdate is not specificied a default
date will be used). Default date must be common
and shall not be modified.
Functions to update and get the different values
A function to decide whether a person is younger
than other
Bibliography
OBJECTS
Creating objects
Objects (instances of a class) can be created:
As local variables
As global variables
As members of other classes
Dynamically
Temporally (to evaluate an expression)
Constructors y destructors
Constructors
Destructors
Derived classes
A class can inherit from any other class:
Example
class Employee
{
string first_name,family_name;
public:
void print() const;
};
class Manager : public Employee
{
public:
void print() const;
};
Class hierarchy
Inheritance relations create a graph-like structure
Virtual functions
Must be redefined (overriden) on any derived class
Keyword virtual
virtual void print () const;
Create abstract classes