CPP Bloque 1 PDF
CPP Bloque 1 PDF
CPP Bloque 1 PDF
Bloques
ANSI/ISO C++ / Fundamentals
POO
librera STL
Patrones de Diseo
UML
C++ online
C++ Shell
http://cpp.sh/
Ideone
http://ideone.com/
Included options:
Standard
Warnings
Optimization level
Standard Input
Coding ground
http://www.tutorialspoint.com/codingground.
htm
C/C++
Gran acierto de C++
Mantener compatibilidad con C: cualquier programa C podra ser considerado
tambin como un programa C++
Mayor acierto tambin es su defecto ms criticado
Se da origen a hbridos donde no existe un modelo de programacin
predominante (POO, Programacin Procedural)
Rapid Quiz
Q 1 - One of the following is true for an inline
function.
Rapid Quiz
Answer : A
Explanation
As inline function gets expanded at the line of
call like a macro it executes faster.
Rapid Quiz
Q 2 - What is the output of the following program?
#include<iostream>
using namespace std;
class abc {
public:
int i;
abc(int i) {
i = i;
}
};
main() {
abc m(5);
cout<<m.i;
}
A-5
B - Garbage
C - Error at the statement i=i;
D - Compile error: i declared twice.
Rapid Quiz
Answer : B
Explanation
i=i, is assigning parameter to itself.
Rapid Quiz
Q 3 - Runtime polymorphism is done using.
A - Function overloading
B - Virtual classes
C - Virtual functions
D - Friend function
Rapid Quiz
Answer : C
Explanation
Virtual functions gives the ability to override the
functionality of base class into the derived
class. Hence achieving dynamic/runtime
polymorphism.
Rapid Quiz
Q 4 - Which feature of the OOPS gives the
concept of reusability?
A - Abstraction
B - Encapsulation
C - Inheritance
D - None of the above.
Rapid Quiz
Answer : C
Explanation
The process of designing a new class (derived)
from the existing (base) class to acquire the
attributes of the existing is called as inheritance.
Inheritance gives the concept of reusability for
code/software components.
Rapid Quiz
Q 5 - What is the output of the following
program?
#include<iostream>
using namespace std;
void f() {
static int i = 3;
cout<<i;
if(--i) f();
}
main() {
f();
}
Rapid Quiz
Answer : B
Explanation
As the static variable retains its value from the
function calls, the recursion happens thrice.
Rapid Quiz
Q 6 - What is the output of the following
program?
#include<iostream>
using namespace std;
main()
{
int a[] = {10, 20, 30};
cout<<*a+1;
}
Rapid Quiz
Answer : C
Explanation
*a refers to 10 and adding a 1 to it gives 11.
Rapid Quiz
Q 7 - Which operator is required to be
overloaded as member function only?
A-_
B-__
C - ++ (postfix version)
D-=
Rapid Quiz
Answer : D
Explanation
Overloaded assignment operator does the job
similar to copy constructor and is required to be
overloaded as member function of the class.
Rapid Quiz
Q 8 - A protected member of the class in
accessible in
Rapid Quiz
Answer : B
Explanation
Only members of the derived class and the
same class can access a protected member.
Rapid Quiz
Q 9 - What is the output of the following
program?
A-5
B-6
C - Runtime error
D - Compile error
#include<iostream>
using namespace std;
main() {
int const a = 5;
a++;
cout<<a;
}
Rapid Quiz
Answer : D
Explanation
Compile error - constant variable cannot be
modified.
Rapid Quiz
Q 10 - What is the output of the following
program?
A-111
B-000
C-321
D-123
#include<iostream>
using namespace std;
void f() {
static int i;
++i;
cout<<i<< ;
}
main()
{
f();
f();
f();
}
Rapid Quiz
Answer : D
Explanation
1 2 3, A static local variables retains its value
between the function calls and the default value
is 0.
Rapid Quiz
Q 11 - In the following program f() is
overloaded.
A - True
B - False
void f(int x) {
x++;
}
int f(signed x) {
return x;
}
main() {
}
Rapid Quiz
Answer : B
Explanation
No, as both the functions arguments is same
and compiler ignores return type to consider
overloading though different in return type.
Rapid Quiz
Q 12 - What is a generic class.
A - Function template
B - Class template
B - Inherited class
B - None of the above.
Rapid Quiz
Answer : B
Explanation
Defining a templated class is defining a generic
class. Hence functionality of the class is
generalized for several types, if applicable.
Rapid Quiz
Q 13 - What is the output of the following
program?
A-31
B-33
C-11
D-13
#include<iostream>
using namespace std;
class abc {
public:
static int x;
int i;
abc() {
i = ++x;
}
};
int abc::x;
main() {
abc m, n, p;
cout<<m.x<<" "<<m.i<<endl;
}
Rapid Quiz
Answer : A
Explanation
The static member variable x shares common
memory among all the objects created for the
class.
Rapid Quiz
Q 14 - What is the output of the following
program?
#include<iostream>
#include<string.h>
A-59
B - 7 20
C - 5 20
D - 8 20
Rapid Quiz
Answer : A
Explanation
Length of the string is count of character upto
\0. sizeof reports the size of the array.
Rapid Quiz
Q 15 - What is the output of the following
program?
A - 73 73
B - 60 13
C - 13 60
D - 60 60
#include<isotream>
using namespace std;
main()
{
int i = 13, j = 60;
i^=j;
j^=i;
i^=j;
cout<<i<< <<j;
}
Rapid Quiz
60 13, its swapping.
C++ Fundamentals
Palabras reservadas
C y C++
const double float int short struct unsigned break continue
else for long signed switch void case default enum goto
register sizeof typedef volatile char do extern if return static
union while
Palabras reservadas
C++:
asm
dynamic_cast
new static_cast
typeid
throw
namespace reinterpret_cast
catch
false
try bool
operator template
virtual delete
mutable protected
true wchar_t
explicit
Variables
Regla
ejemplos no vlidos:
1a
switch
$contador
my var
Enteros
Enteros
[signed | unsigned] [short | long] int
[signed | unsigned] short [int]
[signed | unsigned] long [int]
El lenguaje especifica que un tipo de dato short int debe ser menor o igual en tamao a
un int, el cual deber ser menor o igual a un tipo de dato long int
Enteros
Enteros (Plataforma de 32: 386, 486, Pentium)
Tipo de Dato
Lmites
Memoria
short int
-32.767 a 32.767
2 bytes
0 a 65.535
2 bytes
int
-2.147.482.647 a 2.147.482.647
4 bytes
unsigned int
0 a 4.294.967.295
4 bytes
long int
-2.147.482.647 a 2.147.482.647
4 bytes
0 a 4.294.967.295
4 bytes
Enteros
What will the line of code below print out and
why?
cout << 25u - 50;
Enteros
If the types of two operands differ from one another:
The operand with the lower type will be promoted to
the type of the higher type operand
Type hierarchy:
Nmeros No enteros
Nmeros No enteros
Nmero con parte fraccionaria: float (precisin simple) y double (precisin
doble)
Diferencia entre float y double: la precisin
C++ no especifica un tamao concreto pero s establece que la variable del tipo
float debe ser menor o igual en tamao al tipo double, la cual debe ser menor o
igual a la del tipo long double
Nmeros No enteros
Conversin Implcita
Cualquier nmero decimal es tomado como de
precisin doble.
En el ejemplo, cuando realizamos la asignacin,
el mismo es llevado a precisin simple.
float a
Nmeros No enteros
There are other such constructs such as for example
0UL which means a (unsigned long)0, whereas a plain 0
would be an (int)0.
The .f is actually two components:
Nmeros No enteros
In general a double has 15 to 16 decimal digits
of precision, while float only has 7.
// prints 9.000023
while
double a = 1.0 / 81;
double b = 0;
for (int i = 0; i < 729; ++ i) b += a;
printf("%.15g\n", b);
// prints 8.99999999999996
Nmeros No enteros
No Enteros (Plataforma de 32: 386, 486, Pentium)
Tipo de Dato
Lmites
Memoria
float
10E-38 a 10E38
4 bytes
double
10E-308 a 10E308
8 bytes
long double
10E-308 a 10E308
8 bytes
sizeof operator
Queries size of the object or type.
Used when actual size of the object must be
known.
sizeof( type )
sizeof expression
Both versions return a constant of type std::
size_t
https://gcc.gnu.org/onlinedocs/gcc-5.3.0
/gcc/Typeof.html
sizeof operator
#include <iostream>
struct Empty {};
struct Base { int a; };
struct Derived : Base { int b; };
struct Bit { unsigned bit: 1; };
int main()
{
Empty e;
Derived d;
Base& b = d;
Bit bit;
std::cout << "size of empty class: " << sizeof e
<< '\n'
<< "size of pointer : "
<< sizeof &e
<< '\n'
//
<< "size of function: "
<< sizeof(void()) << '\n' // error
//
<< "size of incomplete type: " << sizeof(int[]) << '\n' // error
//
<< "size of bit field: "
<< sizeof bit.bit << '\n' // error
<< "size of array of 10 int: " << sizeof(int[10]) << '\n'
<< "size of the Derived: " << sizeof d
<< '\n'
<< "size of the Derived through Base: " << sizeof b << '\n';
}
Operator precedence
Operator precedence and associativity helps in
determining the sequence of applicability of operators
when multiple operators act on a operand in an
expression.
x=2+3%4
x = 2 + (3 % 4)
Operator precedence
Operator precedence
Operator precedence
Example:
Exercises:
a) x = 3 + 4 + 5;
b) x = y = z;
c) z *= ++y + 5;
d) a || b && c || d;
Operator precedence
Answers
a) Binary operator + has higher precedence than
=:
x = (3 + 4 + 5);
Binary operator + has left to right association:
Final answer: x = ((3 + 4) + 5);
b) Binary operator = has right to left association:
Final answer: x = (y = z);
switch vs if else
The switch statement is faster to execute than the ifelse-if ladder. This is due to the compiler's ability to
optimise the switch statement.
Speed-test: http://www.blackwasp.co.
uk/SpeedTestIfElseSwitch.aspx
Wswitch-bool
Warn a switch statement has an index of boolean type and the case
values are outside the range of a boolean type. It is possible to
suppress this warning by casting the controlling expression to a
type other than bool. For example:
switch ((int) (a == 4))
{
...
}
This warning is enabled by default for C and C++ programs.
Array
Coleccin de elementos de cierto tipo
El nombre de un array es un puntero que
contiene la direccin de memoria del primer
elemento del array
El chequeo de lmites en un array no es
verificado (como en otros lenguajes)
String en C++
cstrings functions
Check header <cstring> (string.h)
C Strings: this header file defines several functions to manipulate C strings and arrays.
See: http://www.cplusplus.com/reference/cstring/
cstrings functions
Example: copy string
strcpy
char * strcpy ( char * destination, const char * source );
Copies the C string pointed by source into the array
pointed by destination, including the terminating null
character (and stopping at that point).
Functions
Functions
When a program calls a function, program
control is transferred to the called function.
A called function performs defined task
It returns program control back to the main
program when:
Functions
La declaracin de una funcin consiste en
especificar su tipo, su identificador, el tipo de
dato de los parmetros que recibe y su tipo de
dato de retorno. (Prototipo de una funcin)
Passing arguments
Pass by Value
Example
int doSth(int a, int b, int c);
Pass by Reference
Example
int doSth(int &a, int &b, int &c);
Passing arguments
#include <iostream>
using namespace std;
int divide(int numerator, int denominator, int
&remainder)
{
remainder = numerator % denominator;
return numerator / denominator;
}
int main() {
int num = 14;
int den = 4;
int rem;
int result = divide(num, den, rem);
cout << result << "*" << den << "+" << rem << "="
<< num << endl;
//The print on the screen is: 3*4+2=12
}
Array as parameters
just need to add [ ] to the end of declaration
Example
int doSth(int values[], unsigned len);
To call it:
int len = 10;
int values[len];
doSth(values, len );
Constant Parameters
Constant Parameters
Example
Cons:
Defining a parameter as reference avoids ugly
code like (*pval)++.
Necessary for some applications like copy
constructors.
Makes it clear, unlike with pointers, that a null
pointer is not a possible value.
int a = 1;
int f (int);
int g (int x = f(a)); // lookup for f finds ::f, lookup for a
finds ::a // the value of ::a, which is 1 at this point, is not
used
void h()
{
a = 2; // changes the value of ::a
{
int a = 3;
g();
// calls f(2), then calls g() with the result
}
}
form a pointer-to-member or
in a member access expression.
class X
{
int a;
static int b;
int mem1(int i = a); // error: non-static member cannot
be used
int mem2(int i = b); // OK: lookup finds X::b, the static
member
};
class C {
void f(int i = 3);
void g(int i, int j = 99);
C(int arg); // non-default constructor
};
//out-of-class definition (eg: c.cpp)
void C::f(int i = 3) {
// error: default argument already
}
// specified in class scope
void C::g(int i = 88, int j) { // OK: in this translation unit,
}
// C::g can be called with no argument
C::C(int arg = 1) { // error: turns this into a default constructor
}
Inline Functions
Calling a function generally causes a certain
overhead (stacking arguments, jumps, etc...),
and thus for very short functions, it may be more
efficient to simply insert the code of the
function where it is called.
Preceding a function declaration with the inline
specifier suggest the compiler that inline
expansion is preferred.
Code generated by the function body shall be
inserted at each point the function is called
User defined
types
Structures
A data structure is a group of data elements,
known as members, grouped together under one
name.
It is a user-defined type
In the case where object_names are specified,
the type name (product) becomes optional:
struct requires either atype_name or at least one
name in object_names, but not necessarily both.
struct type_name {
type1 name1;
type2 name2;
type3 name3;
} object_names; // optional
struct product {
int weight;
double price;
};
product apple;
product lime, coconut;
Structure Initialization
We can initialize a struct object with braces.
(.) es el member access operator
Example:
struct Automovil_t {
int
id;
unsigned kms;
bool
abs;
};
Automovil_t auto = {1, 0, true};
Expre
ssion
What is evaluated
Equiv
alent
a.b
Member b of object a
a->b
(*a).b
*a.b
*(a.b)
typedef
typedef is a keyword. This is used to define a
new name for an existing data type. The general
form is:
typedef datatype newname;
In C++ there is no need to specify the keyword
typedef for enum, structure and union data
types. (like C)
typedef
// simple typedef
typedef unsigned long ulong;
Unions
A union is a special class type that can hold only
one of its non-static data members at a time.
Unions
The union is only as big as necessary to hold its
largest data member.
The other data members are allocated in the
same bytes as part of that largest member.
The details of that allocation are
implementation-defined, and it's undefined
behavior to read from the member of the union
that wasn't most recently written.
Unions
Unions, example 1
#include <iostream>
union S
{
std::int32_t n; // 4 bytes
std::uint16_t s[2]; // 4 bytes
std::uint8_t c; // 1 byte
};
// the whole union occupies 4 bytes
int main()
{
S s = {0x12345678}; // initializes the first member, s.n is now the active
member
// at this point, reading from s.s or s.c is undefined behavior (UB)
std::cout << std::hex << "s.n = " << s.n << '\n';
s.s[0] = 0x0011; // s.s is now the active member
// at this point, reading from n or c is UB but most compilers define it
std::cout << "s.c is now " << +s.c << '\n' // 11 or 00, depending on platform
<< "s.n is now " << s.n << '\n'; // 12340011 or 00115678
}
more: http://en.cppreference.com/w/cpp/language/union
Unions, example 2
#include <iostream>
#include <stdio.h>
using namespace std;
union u_color {
// first representation (member of union)
struct s_color {
unsigned char a, b, g, r;
} uc_color;
// second representation (member of union)
unsigned int i_color;
};
int main(void) {
FILE *f = fopen("color.dat", "rb");
if (f == NULL)
exit(1);
fseek(f, 0, SEEK_END);
}
Example
enum colors_t {black, blue, green, cyan, red,
purple, yellow, white};
colors_t mycolor;
enum type_name {
value1,
value2,
...
} object_names;
mycolor = blue;
if (mycolor == green) mycolor = red;
enum months {
january = 1,
febrary = 2,
march = 3,
july = 7;
jy = 7; // same value for other option
}
Enum
Setting initial values
enum Months {
january = 1,
february, //2
march,
april,
may,
june,
july,
jl= 7,
august, //8
september,
october,
november,
december
}
Enum
Enums are distinct types, so you can do typeoriented things like overloading with them:
Enum
I like the automatic behavior that can be used
with enums, for example:
Then it is easy to loop until LAST, and when a
new state (or whatever is represented) is added,
the logic adapts.
Version
Versin
v1.2.
Comentario
Versin para curso de C++
CASA, tarde.
Fecha
20/03/2016
Autor
Martnez, Pablo