0% found this document useful (0 votes)
42 views14 pages

Learning C++

This document summarizes key concepts in C++ including variables, data types, operators, flow control, loops, arrays, and pointers. It covers: 1. The basic components and structure of a C++ program including headers, libraries, and the main function. 2. Fundamental data types like int, double, char, and bool and how to declare and initialize variables. 3. Common operators for arithmetic, assignment, comparison, logic, and more. 4. Flow control structures like if/else statements, switch statements, and loops for repetition and iteration. 5. How to define, access, and manipulate arrays to organize related data. 6. An introduction to pointers

Uploaded by

Daniel Cabasa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views14 pages

Learning C++

This document summarizes key concepts in C++ including variables, data types, operators, flow control, loops, arrays, and pointers. It covers: 1. The basic components and structure of a C++ program including headers, libraries, and the main function. 2. Fundamental data types like int, double, char, and bool and how to declare and initialize variables. 3. Common operators for arithmetic, assignment, comparison, logic, and more. 4. Flow control structures like if/else statements, switch statements, and loops for repetition and iteration. 5. How to define, access, and manipulate arrays to organize related data. 6. An introduction to pointers

Uploaded by

Daniel Cabasa
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

Learning C++  Logical Operators

 Code starts with #include <iostream>, a library to understand the - AND (&&) : if one or all is false it will be false
code that will be written with C++ - OR (II): If one or all is true then it will be true
 Main function (main() {}) is the entry code and the code inside the - NOT (!): Negate whatever you gave it
functions will be executed in order.  Output Formatting
3 COMPONENTS OF C++ : - Link for references:
1. Core features EX. Defining variable https://en.cppreference.com/w/cpp/io/manip
2. Standard library EX. #include <iostream> and <string> - #include <ios> and #include <manip>
3. STL – part of c++ standard library, collection of things - std::endl – like a \n and will occupy the new line
TYPES OF VARIABLES: - std::flush – sends the data directly to the device
 Int – whole numbers - std::setw(numWidth) - set the width of the text to make it look
 Double & float – fraction, decimal good when display in screen
 Char – characters - std::right – display the data starting to the right
 Bool – true or false - std::internal – justify
 Void – meaningless / valueless - std::showpos – shows positive and negative sign before the num.
 Auto – auto detect by compiler - std::dec, std::hex, std::oct – shows the number in this format
------------------------------------------------------------------------------------ - std::uppercase, std::lowercase – change the text
CHAPTER 4: OPERATIONS ON DATA: - std::scientific – scientific notation
 Precedence and Associativity - std::setprecision(num) – set the precision of decimal points
- Precedence: which operation is to be done first.
C++ Operator Precedence – search on google
- Associativity: which directions to do the calculations.
 Postfix Increment/Decrement
- var++ / ++var - increment by one only.
- var--/ --var – decrement by one only.
 Compound Assignment
- +=, -=, *=, /=, %= :: shortcut to add, sub, mul, div, rem the
variable itself to another var
 Relational Operators (<, >, <=, >=, ==, !=)
- std::boolalpha – shows true/false instead 1/0
std::sin()
std::tan()
Ref: https://en.cppreference.com/w/cpp/header/cmath
 Weird Integral Types
Chapter 5: Flow Control
 Flow Control Introduction
 If Statements
Syntax: if (condition) {body/ consists of codes;} else {}
 Else If- several conditions
 Switch – testing for several different conditions, num only
Actual Reference: https://en.cppreference.com/w/cpp/io/manip  Ternary Operators
std::cout.unset(std::ios::scientific | std::ios::fixed); // hack to unset to Syntax: var = (condition) ? option1 : option2;
default Equivalent to if;else: if(condition) { var = option1; } else {result
=option2;}
 Numeric Limits Disadvantage: only 2 options.
#include <limits> - to show the range of how much you can represent  Flow Control Summary
a number such as int, float, short int, etc. - If
Std::numeric_limits<numberType::min() or ::max() - Else
Refer: https://en.cppreference.com/w/cpp/types/numeric_limits - Else if
- Switch
 Math Functions - Ternary operator
#include <cmath> - library for some math functions
std::floor() – round down Chapter 6: Loops
std::ceil() – round up  Loops Introduction
std::abs() – absoulute value Pillars of any loop:
std::cos() – trigonometric functions - Iterator
std::exp(num) – exponential value e = 2.71 raised to num - Starting point,
std::log () - reverse of pow, computes the power of base e in default - Test (controls when the loops stops)
std::pow(base, exponent) – (3, 4) - Increment(decrement)
std::sqrt() – square root - Loop body
std::round() – round the num halfway points  For Loop – repetitive task
sytax: for (unsigned int i{}; i < 10; ++i) {codes } Or char message[6] {‘h’, ‘e’, ‘l’, ‘l’, ‘o’}
- This will repeat 10 times  Size of an array
 Range base for loops Depend on the number of elements.
Syntax:  Arrays of characters
int array [] {1, 2, ,3, 4, 5, 6, 7}; STRING LITERAL
for (auto value : array) { Char message [] {“Hello World”};
std:cout << “value : “ << value << std::endl;  Array Bounds
} Std::size() – it may be use to know the number of elements the variable
 While Loop has. It is useful especially in arrays to know the number of elements being
Syntax: size_t i{0} // declaration of iterator listed. //included in standard library.
while (I < 10) {std::cout<<”print”<<std::endl; ++I;} Chapter 8: Pointers
 Do While Loop – runs the body then checks  Introduction to Pointers
Pointers – stores the memory address of a variable.
Pointers can only store the same data type of when it is declared.
Pointers size is 8bytes
 Declaring and using pointers
Syntax: int* p_number {} ; - recommended than not putting
braces.. this initialize with nullptr
Declaring like this:
 Int* p_number, other_num; the first is the only one that is a
Chapter 7: Arrays pointer. Next to it will be an integer variable.
 Introduction to Arrays  But you can write like int* p_num, *p_num1; this are all
Arrays – set up collection in c++ programs, group of things with a pointers
group name Initializing pointers and assigning them data:
- [] use to denote an array  Int int_var{43};
- Example: int scores [10] – group of 10 integers  Int* p_int{&int_var} - & before the var is important to avoid
 Declaring and using arrays error
- Example: float salaries Dreferencing a pointer – this is to see the data assign in the
- \0 – like return 0 pointer
- FOR char arrays: Syntax : cout << * p_example << endl;
Syntax: char message[6] {‘h’, ‘e’, ‘l’, ‘l’, ‘o’, ‘\0’}  Pointer to char
 Program Memory Map Revisited
Cpp file  Compiler  exe file  Memory management momory Releasing and Resetting
(MMU) RAM syntax: delete p_var;
Virtual memory – a trick that fools your program into thinking it is p_var = nullptr;
the only program running on your OS, and all memory resources  Dangling Pointers
belong to it. Pointers to avoid:
A memory map is a standard format defined by the OS. All 1. Uninitialized – not stated what is the value, this will crash
programs written for that OS must conform to it. It is usually when you dereferenced it.
divided into some sections. 2. Deleted Pointers – when dereference the pointer when it is
SYSTEM just deleted, this will lead to crash.
STACK Local variables, function calls,. 3. Multiple pointers pointing at the same address – avoid doing
HEAP Additional memory that can be because when you delete for example the one pointer the
queried for at run time other pointer that use the same address will crash.
DATA Solutions:
TEXT Binary file o Initialize your pointers
o Reset pointers after delete
 Dynamic Memory Allocation o For multiple pointers to same address, make sure the
Allocating memory to be own by our program so we can also use owner pointer is very clear
it later.  When new Fails
syntax: int *num{nullptr} In some rare cases, the ‘new" operator will fail to allocate
num = new int; dynamic memory from the heap. When that happens, and you
have no mechanism in place to handle that failure, an exception
will be thrown and your program will crash. BAD!
 The exception mechanism
 Syntax: for
 Std::nothrow – ideal if you dont want exceptions thrown
when new fails // wil throw nullptr if error.
 Syntax: int * data = new(std::nothrow) int[100000000];
 Null Pointer Safety
 To make sure the pointer contains a valid address
You can use this to check if a pointer is nullptr:
 Syntax: if(pointer) {cout << “Contains valid address”;} else
{“Invalid”}; // or this:
 If (!(pointer == nullptr)) {code} else {code};
 Deleting a nullptr pointer is a no problem
 Memory Leaks
 When we loose access to memory that is dynamically
allocated

 To access pointer array:


Syntax: p_scores[i] or *(p_scores+1)
 To delete dynamic pointer array
Syntax: delete[] p_salaries; p_salaries = nullptr;
 Static array vs dynamic array
 Static: can use std::size(array_var) and range based loops
 Dynamic: cannot use on range based loop and std::size
 Therefore you have to delete it first before using another
value so it will not leak.
 Dynamically allocated arrays
 Arrays allocated on the heap with the new operator. Can also
use the std::nothrow version of new.
 Chapter 9: References
 Introduction to References
Reference – an alias variable that can use to reference and
use the original variable.
 Declaring and using references
Syntax: int value{55};
Int& reference_to_value_1{value}; //can be assign to
initialization or assignment
// Modifying data directly: changes reflect even in references
// Modifying in reference will change the value of the original
variable
 Comparing pointers and references
Pointer – store the address of the variable and we can also
modify it through it

Chapter 10: Character Manipulation and Strings


Character Manipulation
Documented in:
https://en.cppreference.com/w/cpp/header/cctype
 References and const <cctype> - library of these ff:
Non Const reference – it can modify the original variable std::isalnum – check whether the character is alphanumeric
Const – cannot modify the original variable. std::isalpha – check if character is alphabetic
std::isblank – check if a character is blank or (space).
std::isdigit - check if the character is a digit.
C-string manipulation #include <string> - if using std::string
https://en.cppreference.com/w/cpp/header/cstring string var (“string content”, numOfChar);
<cstring> / <string.h> - librabry for c-string manipulation string var (numOfCopies, ‘char’);
strlen – use to determine the number of char in a string. string var (“string content”, startingIndex, numOfChar);
doesnt include terminating char, which sizeof does.
strcmp – compares two string. strncmp (lhs, rhs). Declaring and using std::string
strncmp – compares a certain number of characters from two
string. Chapter 11: Functions
strncmp (lhs, rhs, number) The One Definition Rule
// lhs – left hand string, rhs – right hand string o One definition and variable declaration only in a cpp file
Output: and even in other cpp file in the same folder.
0 – equal, negative – lhs before rhs, pos – lhs after rhs o The same goes for function, one definition only.
strchr – find a first occurrence character in a string -
(strchr(string, targetChar)) ptr_var must be incremented by 1 Function Declaration and Function Definitions
to search other target char in string one by one.  It is better to declare the function at the top and define it
strrchr – find last occurrence. below the main function.
ptr_var – can be added by one, this will read the next char in
 the prototype: (int max(int a, int b);) or (int max(int , int );)
the string.
can be declare at the top and later define below the main
function.
C-String concatenation and copy
strcat(var1, var2) – concatenate the var2 strings to var1
Multiple Files - Compilation Model Revisited
\0 – terminate the array.
 Preprocessing – this will copy the library code you use and
strncat (var1, var2, numChar) – concatenate but with a
paste to your source file.
specific number of character in var2.
 Compilation – this will turn your source code into a binary
strcpy (desVar, sourceVar) – copy source var into destination
executable.
var.
 Linking – all of your source file that turn to object after
strncpy (desVar, sourceVar, num) – copy a specific number of
compilation will be merge into a single object that can be run.
char from source var into destination var.
-SPLITTING YOUR CODE/PROGRAM ACROSS DIFFERENT FILES-

Introducing std::string
NOTE: You can create a header file (e.g. header.h) that can be a //when calling
container for your prototype function : (int max(int a, int b);) or int main () {
(int max(int , int );) and you can also put the definition of say_age (age);
function in other cpp file. Remember to include the header.h // the argument that’s going to will be the address since you
(#include “header.h”) in the main cpp file so it will load the put (&) in the paremeter of the say_age function.
function from the header file. return 0;
}
Pass by value
parameter – the passing value in the function.
argument – the passing of value to a function (when calling) Chapter 12: Getting Things out of functions
&varName – using this as a parameter makes the variable Introduction to getting things out of functions
changeable inside and outside the function as this gets the Input and output parameters
address of the variable. Returning from functions by value

Pass by pointer Chapter 13: Function Overloading


when passing by pointer: Function Overloading Introduction
syntax: - Can use the same name function but should be different
int funcName (int *age) { types. (E.g. int varName (), double varName (), string
} varName () ).
main () { Overloading with different parameters
int age {23}; - in order to use the same name function (overloading), it must
funcName (&age); have a different data type parameters than the other same
} name function.
NOTE: Unlike when passing a non-pointer, you must pass the
address of the argument variable. (&age).
To dereference a pointer, use (*age) so you can modify or
see what it contains. To change where the pointer points, use
(age) normally, this is the address of the pointer.
Pass by reference Chapter 14: Lambda functions
Syntax of function: Intro to Lambda Functions
int say_age (&age) {}
 A mechanism to set up anonymous functions (without the capture list in lambda function ([]) is used to access
names). Once we have them set up, we can either give them the other variable outside the lambda function.
names and call them, or we can even get them fo do things NOTE: When capturing a variable, it will only be the copied
directly. version of the variable, even after you modify the variable you
capture oustside the lambda function, it will show the earliest
Declaring and using lambda functions value of it not the modified version. Unless you use reference
Syntax: [] () { cout << “Hello World!” << endl;}; ([&var](){}) this will show even the modified version of the
// We can assign it to a variable so we can call it. captured variable.
auto func = [] () { cout << “Hello World!” << endl;}; Capture all in context
func (); // just like a normal function when calling Syntax:
Syntax: // When calling directly without even giving a name [=](){} – this will capture all, but only the copy version of it.
[] (double a, double b) { [&](){} – this will capture all through reference.
cout << “a + b : ” << (a + b) << endl;
} (12.1, 2.5); Chapter 15: Function Templates
Intro to function templates
Function Template –
o it will generate the function when called.
o use as better alternative, easier and solution for code
repetition (which is bad).
o it is not a c++ code but the blueprint and way, compilers
make function.
syntax:
template <typename T>
T maximum (T a, T b) {
return (a > b) ? a : b;
}
Trying out function templates

Capture lists
Template specialization

- template specialization is used to bypass the default method of


making template functions. Example is above.
- it comes handy when you are going to work with pointer.
- Remember: with the default template function, it will be disaster
if you compare two pointers.

Template type deduction and explicit arguments


 Template type deduction – explicitly say that we wanted that
Chapter 16: C++20 Concepts Crash course
data type to be returned even if one or all variable are not Intro to C++20 Concepts
the same data type unless between string and numbers.
Syntax :
in the declaration, it is just like a normal tamplate function
but the difference is when it is called.
funcName<double(DataType)>(var1, var2)

Template parameters by reference


o difference with non reference parameters is that it has
const before ‘T’.
syntax:
template <typename T>
const T& funcName (const T& var1, const T&var2) { } Concepts – A mechanism to place constraints on your template
type parameters.
2 Types of concepts:
 STANDARD BUILT IN CONCEPTS – built in, examples Library - #include <concepts>, #include <type_traits> - if
are from above. going to use type traits codes.
LIBRARY: #include <concepts> syntax:
syntax1: template <typename T>
template <typename T> concept (conceptName) = requires (parameters needed)
requires std::integral<T> {code to check whether the parameters can execute
T add (T a, T b) {} without error.}
Note: This will only work if the requirement is satisfied which Note: your own concepts can be used just like a standard
is integral types . concept.
Integral – char, int whether signed or unsigned, long or short. My Insight with concepts: CONCEPTS are use to check
floating – float, double. your variables, data types or some code syntax if it is
static_cast – convert data type from one to another. proper and without error according to the constraints
syntax: static_cast<datatype to convert>(VarName) you put. If the compiler finds error/s, it will not
static_assertion – a way to check if a condition is true when successfully compile and warns you beforehand.
the code is compiled. Note that it needs to be a constant
expression. Zooming in on the requires clause
syntax2: (alternative)  Simple Requirement – Expressions only checked for valid
template <std::integral T> syntax.
T add (T a, T b) { syntax:
return a+b; template <typename T>
} concept TinyType = requires (T t) {};
syntax3:  Nested Requirement – there is another requirement inside
auto add(std::integral auto a, std::integral auto b) { the body of the concept.
return a + b; syntax:
} template <typename T>
syntax4: concept TinyType = requires (T t) {
template <typename T> sizeof(T) <= 4;
T add (T a, T b) requires std::integral<T> {} requires sizeof(T) <= 4;
 CUSTOM CONCEPTS – };
 Compound requirement -
Combining C++20 Concepts
 Concepts can be combined with the logical operators && and
||  public – accessible outside the class
 syntax:  private (default) – accessible only inside the class.
 requires integral<T> || floating_point<T>

Chapter 17: Classes


Intro to classes
 Classes – used to create own data types and use it just like
built in data types.
NOTE: Classes are like blueprint of an object and with this we
can create the object.
 For example, you have a class of person which for example C++ Constructors
has names, address, age, body and etc. with this you can
make your built class to jump or any other things.
Your First Class
syntax:
class Cylinder {
public:
double base_radius {1.0;
double base_radius {1.0};
public:
double volume() {
return PI * base_radius * base_radius *
height;
}
};
Defaulted constructors Class Across Multiple Files
syntax:  Just like the past lesson, when linking another header file to
Cylinder() = default; the main cpp file you have to include it (#include “header.h”)
NOTE: You have to put default constructors in your class if you however at some point if you have a header file that also
put another constructor especially if you want to use it even if needed the other header file, you can’t include it like in the
you don’t have to put parameters. main file. To do this:
 Your constructors have to be in public so it can be used #ifndef HEADER_H (ifndef - if not define)
outside. #define HEADER_H
{code}
Setters and Getters #endif
 Methods to read or modify member variable of a class. NOTE: This will be like a guard incase the header file included in
two file to avoid error.

Arrow pointer call notation


 We can store a class in the heap and point it in the pointer
Syntax: Cylinder* p_cylinder1 = new Cylinder(100,100);
 Then we can use the arrow pointer call notation to
dereference it (->).
 SETTERS - Use to modify the data members inside the class.
Syntax:
 GETTERS – Use to read the data members from inside of the
p.cylinder1->volume()
class to outside.
// or use *
(*p_cylinder1).volume() }
//To Access
Destructors dog1.funcName1(“String”, 6)->funcName2(“String”, 7); //if *
dog1.funcName1(“String”, 6).funcName2(“String”, 7);// if &

struct
it is also like a class but the only difference is struct default
members are public while class default members are private.
Syntax:
struct Cat {
string name;
}

Size of objects

Order of Constructor Destructor Calls


 Constructor will be run in order first one will run first. But
Destructor will delete in reverse.
The this Pointer
this – return the memory of the current object
syntax:
Dog*(or &) funcName1 (string strParam, int intParam) {
name = strParam;
age = intParam;
return this; // this will return a memory address
return *this; // if using &
}
Dog*(or &) funcName2 (string strParam, int intParam) {
name = strParam;
age = intParam;
return this; // this will return a memory address

You might also like