C++
Explain Constructors
" special kind of method that enables control regarding how the objects of a class should be created" special member functions of a class, executed whenever new objects are created within that class. "it basically prepares new objects for use" *name is identical to that of class, and no return type /void - a default constructor has no parameters, but can have parameters added which makes it possible to assign an initial value to an object when its created.
Explain encapsulation
"Encapsulation means that objects keep their state information private. Rather than directly manipulating an object's data, other objects send requests to the object, in the form of messages, some of which the object may respond to by altering its internal state."
the rand() function the srand() function
#cstlib <cstlib> rand() rand() % 6 // #'s 1-6 random srand() // truly random numbers - allows you to specify the seed value as its parameter
define a variable PI equal to 3.14 that uses no space in memory
#define PI 3.14
Char library functions: ctype
#include <cctype>
Define Char Arrays
#include <cstring> a memory location where we can store one character value * must be large enough to include the null value '\0' * when traversing a string using a loop, make sure to stop at the null character! *also don't write strings larger than the size of the array
opening and reading from a file
#include <fstream>
which header allows us to avoid using std:: cout all the time?
#include <iostream>
Introduction to STL vector
#include <vector> -can hold values of any type vector <int> scores; // use [ ] to access elements To add elements to vector: vector <int> scores {10, 20, 30}; Other info: .push_back(); .size(); .pop_back(); .clear();
Difference between & and *
&(ampersand) - "address in memory" - returns the memory address of its operand... ex: int num = -99; &num // prints address in hexadecimal - anything done to reference variable also happens to the original ex: int &sonny = sonquio; *(dereference operator) - returns value of the variable (" used to obtain the value pointed to by a pointer variable") ex: int gum = *pointer;
Passing Dynamically allocated arrays to functions
* only if the function handles the same type ex: using bubble sort function
Write code that sorts two numbers chosen by the user using pointers
* simply writing code that passes to a function wont' work because we aren't working with the original values when passed to a function. We must use pointers!
How do you compare C-Strings?
* you must compare characters and not addresses!
compute sum of ip1 + ip2 and assign to ip3
*ip3 = *ip2 + *ip1
add 22 to the variable that strikecounter is pointing to
*strikecounter += 22;
End of File (EOF)
- returns nonzero (meaning TRUE) when there are no more data to be read from an input file stream - returns zero (meaning FALSE)
Vectors
- the data type of its elements must be declared -once created, the type cannot change! * can only store values of the same type! syntax: vector <type> name; ex: vector <int> numList(number of number); // declare vector size int myFun(vector <int> &v){ // & not necessary! } ***don't return vectors inside functions! it creates a copy and really slow... just pass vector by reference! ex: name.size() - name.push_back() - add to the back -name.pop_back() - remove from the end
2D Array as a parameter, argument
- use array name as argument in function call getExams (exams, 2); use empty [] for row, size declarator for column in prototype void getExams (int [] [COLS], int); // prototype void getExams (int exams [] [COLS], int rows) //header ex: Picture
Operator Overloading
- we can define the behavior for all (most) operators > can make standard syntax for OUR objects (classes)
Explain what is the logic flow here: int jellydonuts; getOrder(jellydonuts); void getOrder(int &donuts){ ... }
-the address of jellydonuts is stored in the donuts parameter - the donuts parameter points to the variable jellydonuts
Define an Array, and one simple example
-used to store a collection of data that are all the same type ex: int b[5] = { 11, 12, 13, 14, 15};
C++ Features
...is an open ISO-standardized language.For a time, C++ had no official standard and was maintained by a de-facto standard, however since 1998, C++ is standardized by a committee of the ISO. Their page may be accessed here. ...is a compiled language.C++ compiles directly to a machine's native code, allowing it to be one of the fastest languages in the world, if optimized. ...is a strongly-typed unsafe language.C++ is a language that expects the programmer to know what he or she is doing, but allows for incredible amounts of control as a result. ...supports both manifest and inferred typing.As of the latest C++ standard, C++ supports both manifest and inferred typing, allowing flexibility and a means of avoiding verbosity where desired. ...supports both static and dynamic type checking.C++ allows type conversions to be checked either at compile-time or at run-time, again offering another degree of flexibility. Most C++ type checking is, however, static. ...offers many paradigm choices.C++ offers remarkable support for procedural, generic, and object-oriented programming paradigms, with many other paradigms being possible as well. ...is portable.As one of the most frequently used languages in the world and as an open language, C++ has a wide range of compilers that run on many different platforms that support it. Code that exclusively uses C++'s standard library will run on many platforms with few to no changes. ...is upwards compatible with CC++, being a language that directly builds off C, is compatible with almost all C code. C++ can use C libraries with few to no modifications of the libraries' code. ...has incredible library support.A search for "library" on the popular project-management website SourceForge will yield over 3000 results for C++ libraries. A link to the results of the search may be found here.
What usually goes into .h files and .cpp files?
.h files (header file) - class definitions - data members and member function declarations .cpp files (source file) - implementation of class and its methods -defines "how" it will perform those features -to use a class, one must include the class's header file -member function definitions
int score = 5; int *scorePtr; scorePtr = &score; cout << scorePtr << endl; cout << *scorePtr << endl; cout << score << endl; what is the output?
0x29fee8 5 5
pointer to constants (1) constant pointers(2) constant pointers to constants (3)
1. to store the address of a constant in a pointer 2. initialized with an address and cannot be modified int value = 22; int *const ptr = &value 3. int value = 22; const int const *ptr = &value;
Using SMART pointers to avoid memory leaks - explain unique_ptr
3 types 1. unique_ptr 2. shared_ptr 3. weak_ptr Syntax unique_ptr <int> ptr(new int); Unique Pointer - can be created to own the memory resource that is acquired dynamically - can transfer ownership to another unique pointer, but no two unique pointers can own the same memory resource at the same time - when a unique_pointer goes out of scope, the memory resource will be released automatically
4x the value of the variable that strikecounter is pointing to
4 ** strikecounter;
Input string stream
<iostream> <sstream> <string> reading input data from a string rather than from a keyboard 3 steps: 1. declare a new string stream variable and initialize the string streams buffer to copy of string userInfo string userInfo = "Amy Smith 19"; istringstream inSS(userInfo); string firstname; string lastname; int userage; 2. then the program extracts the data form stream inSS using >>, similar to extracting from cin. inSS >> firstname; inSS >> lastname; inSS >> userage;
What is a class?
A class is the blueprint from which individual objects are created. A class name describes 1. attributes (data, contain information about an instance of the class) 2. behavior of an object ( method). ex: A Banking Program name: Bank Account attributes: account number, balance, dateOpened behavior: open(), close(), deposit()
Returning pointers from functions
A pointer can be the return type of a function: int * newNum(); Note: the function must not return a pointer to a local variable in the function! A function should only return a pointer to data that was passed to the function as an argument or to DAM.
How to iterate through a 2D array?
Must use nested loops, outer loop iterating through rows and the inner loop iterating through columns in rows.
Function Overloading
Process of creating several functions with the same name but different formal parameter lists.
Memory is composed of?
Stack and Heap
Memory Types
Static Memory ( compile time) -declared outside any function - or declared in class with static keyword > done when one data item is shared by all instances fo the class, lives before program and ends with program Automatic Memory ( on activation record) - function parameters and local variables - goes away when the function exits Dynamic Memory ( doesn't go away unless you say so! ) - Allocated with new or new[ ] - de allocated with delete or delete [ ] Thread Memory - allocated for multithreaded programs
Step through the elements of an array using a Range-Based For Loop? Whats the difference between Ranged Based For Loop and For Loop?
The Range-Based For Loop for ( dataType rangeVariable : array) ---------statement; * to modify the contents of an array using the range-based for loop you must declare the range variable as a reference.
What happens when you compile a code?
The executable file will be loaded to computer memory and the CPU executes the program's instruction one at a time!
Access Specifier
The keywords public, private, and protected, which determine how an identifier can be used.
unsigned long
Unsigned long variables are extended size variables for number storage, and store 32 bits (4 bytes). Unlike standard longs unsigned longs won't store negative numbers, making their range from 0 to 4,294,967,295 (2^32 - 1).
Recursion
When a function calls itself. - method of solving a problem where the solution depends on the solutions to smaller instances of the same problem.
using getline() with string streams
a common use of string streams is to process user input line by line
What is the difference between float and double?
a float has 7 decimal digits of precision a double is a double precision floating point (15 dec precision)
How do you use an array as a parameter
a function that receives an array as a parameter must also receive the size ex: void doSomething (int array[], int size);
Define Functions
a group of statements that perform a particular task
What is a C string?
a sequence of characters ending with a null character '\0'
Functions with struct parameters
a variable of a struct type can be a function parameter - pass by value = copies
Pointers
a variable with an address of another variable as its value - stores memory address of something else ex: int x = 5; variable x is stored in "ox29fee8"
Struct ( define, how is memory allocated, data types, and what is its power?)
a variable with data members :) *it just declares new type, no memory is allocated *it can contain multiple data types related to a single entity syntax: struct TimeHr Min { int hourvalue; int minvalue; }; TimeHrMin runTime1; runTime1.hourvalue = 5; The Structs Power: - evident when used in functions as it can be used to return multiple values ex: using a struct that is returned from a function, the structs data members are copied upon return
Pointer Variable
aka "pointer" - a variable that holds an address of another piece of data, it points to the data
new int;
allocates memory necessary for storing an integer on the heap, and returns that adress
What is DATA hiding?
an object only reveals what the other application components require to effectively run the application. All else is kept out of view.
Initializing Struct Variables ScoreInfo pete = {} // explain what we just did
array of chars is initialized to null and the double to 0.0
Function arguments Pass by reference vs pass by value
by value: copies the arguments actual value into the function's formal parameter. Here we can make changes to the parameter within the function without having any effect on the argument by reference: this method copies the arguments reference into the formal parameter. Within the function, the reference is used to access the actual argument used in the call. This means that any change made to the parameter affects the argument. C++ uses call by value to pass arguments by default
output string stream
can insert characters into a string buffer using << ostringstream
What is the difference between a char and string?
char = single character string = sequence of characters
Conditional (Ternary) Operator
condition ? expr1 : expr2 > If condition is true, the operator returns the value of expr1 > otherwise, it returns the value of expr2
Function declaration vs definition
declaration, usually stored in header file (hpp or .h) definition, usually stored in .cpp file * if the file containing main needs to be recompiled, the file containing definitions doesn't.
namespaces
defines a region used to prevent name conflicts - name conflicts are when two or more items like variables, classes or functions have the same name Data Structures Class: - Namespaces create unique scopes, and items declared within a scope are accessible within that scope - Why use them? > names from one scope don't conflict with other scopes > no conflicts between items in different namespaces
What does delete, delete?
delete only deletes the memory allocated to the variable, it doesn't delete the pointer! Leading to dangling pointers!
Sum and Average the Array elements
double average; int tnum; int sum = 0; for (tnum = 0; tnum< SIZE; tnum++) sum += tests[tnum]; average = sum / SIZE
Passing arrays to functions as an argument write a code that passes an array with numbers 1-8 to a function that prints out the array
ex: void printarray (int arr[], int size) { ... } int main () { int myarr[3]= {1,2,3]; printarray(myarr, 3); // without brackets when passing as an argument to a function } to define a function that takes an array parameter function prototype void fxname (int []); function header void fxname ( int tests []); * an array is not changed by a function
Comparing pointers ptr1 == ptr2 vs *ptr1 == *ptr2
first compares addresses second compares contents
sizeof()
gets variable or data type's size, in bytes. - can be used to determine size of array... ex: char c; cout << sizeof(c) << endl;
Multidimensional array
holds one or more arrays! ex: int x [3][4]
if statement while loop for loop the do ... while loop switch statement
if, tests for an expression for truth, it executes if true * if expressions don't need semicolon! while, executes as long as the condition is true ( * they may never run at all!) for loop, gives you full control and executes a specific # of times. - it has 3 components: for (int i = 0; i<10; i++) { do ... while loop, (*guaranteed to execute once, before evaluating the expression). switch, allows a variable to be tested for equality against a list of values.
Why is it good practice to assign NULL to a pointer variable when you declare it?
in case you don't have the exact address to be assigned! int *ptr = NULL;
Static Data Members
independent of any class object, and can be accessed without creating a class object. - must be declared inside class definition, but also be defined outside the class declaration * a public static data member can be accessed outside the class using the scope resolution operator: ClassName::variableName
eof() with input streams
input streams have eof ( ), returns true or false depending on whether the end of the stream is reached... while (inSS >> data) { cout << data << endl; }
Swap pointers xp and yp
int * temp = xp; xp = yp; yp = temp;
Dynamic Memory for Arrays
int *p = NULL; p = new int[20]; delete[]p;
Create a pointer to an int
int *ptr // declaring a pointer to integer ptr
Allocate memory in the heap for an int, point to it with 'ptr' and then free memory
int *ptr = new int; delete ptr;
Find the Highest Value in an array
int count; int highest; highest = numbers [0] for (count = 1; count < SIZE; count++) { if (numbers[count] > highest) highest = numbers[count] } * similar to finding lowest, just reverse the > sign to <`
Use a for loop to calculate the sum of all elements of an array int arr[] = {10, 11, 12, 13 };
int sum = 0; for (int x =0; x<5; x++) { sum += arr[x]; } cout << sum << endl;
The Relationship between Arrays and Pointers
int vals [] = {4, 7, 11}; Array name can be used as a pointer constant ex: cout << *vals; // prints 4 Pointer can be used as an array name ex: int *valptr = vals; cout << valptr[1]; // prints 7
make ip point to the element in the array indexed by section
ip = &enrollment [section]
static variable
is allocated in memory only once and have a global scope, which means they can be accessed anywhere in the program.
cin.ignore () is used when?
is used to consume the newline character especially when you use cin.getline and cin together??? cin.getline() - doesn't skip white spaces and stops at newline cin >> - skips white spaces until it sees a character that fits the data type fo the variable. Only stops until it sees a character that doesn't fit the type, doesn't consume newline! - so we just cin.ignore to consume the newline
Stack
local variables are stored here
How do you access the last array?
n-1
How do you copy one array to another array? Say one array is called newTests and the other is called tests.
newTests = tests is wrong! for (i = 0, i < ARRAY_SIZE; i++) newTests[i] = tests[i];
Passing arrays as arguments to a function
numbers [] = {1,23,4,5}; showValues ( numbers, SIZE); void showValues ( int values [], int size) { for (int count = 0; count < size; count++){ cout << values[count] << edl; } } - c++ stores the address of numbers in the values parameter, and the values parameter points to the numbers array
input stream errors
occur when insertion or extraction fails, causing the stream to enter an error state - a stream internally uses several 1-bit error flags to track the state of the stream. we can check the status or clear ( )
Vector ADT (Abstract Data Types) + Functions
of an ordered, indexable list of items To declare: vector <T> vectorName ( ) :
How to prevent overflow when populating an array?
one way is to keep a counter
prefix vs postfix
prefix -- increments the value, then proceeds with the operation postfix -- evaluates the expression, then performs the increments
buffer manipulators
printing characters from the buffer to the output device requires a time consuming reservation of processor resources, and once reserved ... then they are moved. ---> but if we don't want to wait ... endl and flush endl -inserts newline into the output buffer and informs the system to flush the buffer flush -informs the system to flush the buffer
type casting (conversion)
programmer explicitly indicates that a value is to be converted to another type
list.push_back() vs list.emplace_back()
push_back creates an intermediate copy, wasting a bunch of time
Function declaration
required when you define a fxn in one source file and you call that fxn in another file
Invariants
rule by which the class works - valid for most every function - constructor is an exception!
::
scope resolution, it can access private data members
size_t.
size_t is an unsigned integer data type which can assign only 0 and greater than 0 integer values. It measure bytes of any object's size and returned by sizeof operator. const is the syntax representation of size_t , but without const you can run the program Data Structures: - size_t is platform specific , int is platform agnostic?
What is the flow of C++?
source code pre-processor compiler linker executable (a.out)
int *p = new int; *p = 5;
storing allocated memory in a pointer, and assigning it value of 5.
Processing Array Contents tests[i] ++ vs tests[i++]
tests[i] ++ - adds 1 to tests[i] tests[i++] -increments i
cout stream vs istream
the insertion operator (<<) converts the string literal to characters, temporarily storing characters in an output buffer. The system then writes the buffer's content to the screen. istream >> - skips leading white spaces
Data Abstraction
the process of providing only essential information to the outside world, a process of representing essential features without including implementation details.
What is the function of a function parameter?
they are placeholders for values passed to the function and act as variables inside the function
Heap
this is unused program memory, to dynamically allocate memory
Define Parallel Arrays
two or more arrays that contain related data and of same size! - arrays may be of different types - and use subscript to relate arrays, same subscript = related!
Using range based for loop with vector
vector <int> numbers {10, 20, 30, 40}; To display the vector elements for (int val : numbers) cout << val << endl;
initialize a vector size 30 and set all values to 0
vector <int> scores (30, 0);
Initializing Pointers
we can initialize at the definition time int num, *numptr = # note: cannot mix data types double cost; int *ptr = &cost // this won't work!
how do you find the length of a c string?
we could take advantage of string library functions ex: unsigned long count = strlen (name); cout << count;
How to create an array whose size is unknown at the time of writing your code?
we must create the array dynamically using new
Write code that swaps using pointers as Function Parameters
works like reference variable to allow change to argument from within function void swap (int *x, int *y) { int temp; temp = *x; *x = *y; *y = temp; } int num1 =2, num 2 = -3; swap (&num1, &num2);
How do you print the contents of an array? In english
you must print element by element, but only for char arrays you may use cout << array_name << endl;