cplusplus
In concurrent programming, what are the 4 steps to using a mutex?
"1. Include the <mutex> header 2. Create an std::mutex 3. Lock the mutex using lock() before read/write is called 4. Unlock the mutex after the read/write operation is finished using unlock()" -- udacity C++ nd213-C5-L3-S2
In memory management, what are the four most common copy-ownership policies?
"1.1. No copying policy 1.2. Exclusive ownership policy 1.3. Deep copying policy 1.4. Shared ownership policy" -- https://www.deleaker.com/blog/2018/11/20/copy-semantics-and-resource-management-in-cpp/
In OOP what is function hiding?
"A derived class hides a base class function, as opposed to overriding it, if the base class function is not specified to be virtual." -- Udacity C++ nd213-L2-S20
What are the 3 parts of a lambda function?
"A lambda formally consists of three parts: a capture list [] , a parameter list () and a main part {}, which contains the code to be executed when the Lambda is called. Note that in principal all parts could be empty." -- udacity C++ nd213-C5-L1-S4
How does memory frame compare to a memory page?
"A memory frame is mostly identical to the concept of a memory page with the key difference being its location in the physical main memory instead of the virtual memory." -- Udacity C++ nd213-C4-L2-S5
What is a memory page?
"A memory page is a number of directly successive memory locations in virtual memory defined by the computer architecture and by the operating system. The computer memory is divided into memory pages of equal size. The use of memory pages enables the operating system to perform virtual memory management. The entire working memory is divided into tiles and each address in this computer architecture is interpreted by the Memory Management Unit (MMU) as a logical address and converted into a physical address." -- Udacity C++ nd213-C4-L2-S5
In CS, what is a process?
"A process (also called a task) is a computer program at runtime. It is comprised of the runtime environment provided by the operating system (OS), as well as of the embedded binary code of the program during execution. A process is controlled by the OS through certain actions with which it sets the process into one of several carefully defined states." -- udacity C++ nd213-C5-L1-S2
What does the "Blocked" state of a process indicate?
"A process that is blocked is one that is waiting for an event (such as a system resource becoming available) or the completion of an I/O operation." -- udacity C++ nd213-C5-L1-S2
What does the "Blocked suspended" state of a process indicate?
"A process that is blocked may also be swapped out of main memory. It may be swapped back in again under the same conditions as a "ready suspended" process. In such a case, the process will move to the blocked state, and may still be waiting for a resource to become available." -- udacity C++ nd213-C5-L1-S2
What does the "New" thread state indicate?
"A thread is in this state once it has been created. Until it is actually running, it will not take any CPU resources." -- udacity C++ nd213-C5-L1-S2
What does the "Blocked" thread state indicate?
"A thread might be in this state, when it is waiting for I/O operations to complete. When blocked, a thread cannot continue its execution any further until it is moved to the runnable state again. It will not consume any CPU time in this state. The thread scheduler is responsible for reactivating the thread." -- udacity C++ nd213-C5-L1-S2
What does the "Ready" state of a process indicate?
"After its creation, a process enters the ready state and is loaded into main memory. The process now is ready to run and is waiting for CPU time to be executed. Processes that are ready for execution by the CPU are stored in a queue managed by the OS." -- udacity C++ nd213-C5-L1-S2
In concurrent programming, how will thread exit if the `.detach()` method is called and the program exists while the thread is still executing?
"Also, we do not want our program to terminate with threads still running. Should this happen, such threads will be terminated very harshly without giving them the chance to properly clean up their resources - what would usually happen in the destructor. So a well-designed program usually has a well-designed mechanism for joining all threads before exiting." -- udacity C++ nd213-C5-L1-S3
In memory management, what is automatic memory allocation?
"Automatic memory allocation is performed for function parameters as well as local variables, which are stored on the stack. Memory for these types of variables is allocated when the path of execution enters a scope and freed again once the scope is left." -- Udacity C++ nd213-C4-L3-S2
What is the name for function that takes a variable number of arguments.
"Before C++11, classes and functions could only accept a fixed number of arguments, which had to be specified during the first declaration. With variadic templates it is possible to include any number of arguments of any type." -- udacity C++ nd213-C5-L1-S5
In memory management, what is a copy-ownership policy?
"Before a resource is acquired or after it has been released, the handle must take on a special value indicating that it is not associated with the resource. It is usually zero, sometimes -1, casted to the type of handle. In any case, such a handle will be called null handle. The class that manages the resource must recognize the null handle and not try to use or release the resource in this case." -- https://www.deleaker.com/blog/2018/11/20/copy-semantics-and-resource-management-in-cpp/#id-basic-copy-ownership-policies
In lambda functions, by default, can the variables in the captures list be modified?
"By default, variables in the capture block can not be modified within the Lambda. Using the keyword "mutable" allows to modify the parameters captured by copy, and to call their non-const member functions within the body of the Lambda. The following code examples show several ways of making the external variable "id" accessible within a Lambda." -- udacity C++ nd213-C5-L1-S4
What does Bjarne Stroustrup say about the danger of C vs C++?
"C makes it easy to shoot yourself in the foot; C++ makes it harder, but when you do it blows your whole leg off".
In memory management, what is dynamic memory allocation?
"Dynamic memory allocation is a possibility for programs to request memory from the operating system at runtime when needed. This is the major difference between automatic and static allocation, where the size of the variable must be known at compile time. Dynamic memory allocation is not performed on the limited stack but on the heap and is thus (almost) only limited by the size of the address space." -- Udacity C++ nd213-C4-L3-S2
In C++, what is difference between an `&` on the right side of the equation vs the left?
"For the `&` symbol, if it appears on the left side of an equation (e.g. when declaring a variable), it means that the variable is declared as a reference. If the & appears on the right side of an equation, or before a previously defined variable, it is used to return a memory address" -- Udacity C++ course
In C++, what is a callable object?
"In C++, callable objects are object that can appear as the left-hand operand of the call operator. These can be pointers to functions, objects of a class that defines an overloaded function call operator and lambdas (an anonymous inline function), with which function objects can be created in a very simple way. In the context of concurrency, we can use callable objects to attach a function to a thread." -- udacity C++ nd213-C5-L1-S3
In memory management for C++, what are the formal terms for the types memory used?
"In the available literature on C++, the terms stack and heap are used regularly, even though this is not formally correct: C++ has the free space, storage classes and the storage duration of objects." -- Udacity C++ nd213-C4-L3-S3
In memory management, how does an "Exclusive ownership" copy-ownership policy work?
"In this case, during the implementing of copying and assignment, the resource handle moves from the source object to the target object, that means it remains in a single copy. After copying or assignment, the source object has a null handle and cannot use the resource. The destructor releases the acquired resource. In C++11, this is done in the following way: regular copying and copy assignment are prohibited in the manner described above, and move semantics are implemented, that is, the move constructor and the move assignment operator are defined. (More about move semantics on.)" -- https://www.deleaker.com/blog/2018/11/20/copy-semantics-and-resource-management-in-cpp/#id-exclusive-ownership-policy
What does the "Runnable" thread state indicate?
"In this state, a thread might actually be running or it might be ready to run at any instant of time. It is the responsibility of the thread scheduler to assign CPU time to the thread." -- udacity C++ nd213-C5-L1-S2
What are Initializer lists?
"Initializer lists initialize member variables to specific values, just before the class constructor runs. This initialization ensures that class members are automatically initialized when an instance of the class is created." -- Udacity C++ nd213-C3-L2-S12
What are Lvalues?
"Lvalues have an address that can be accessed. They are expressions whose evaluation by the compiler determines the identity of objects or functions." -- udacity C++ nd213-C4-L5-S2
"The constructor function of a class is a special member function that defines any input parameters or logic that must be included upon instantiation of a class. From what you've seen so far is it required to define a constructor in C++ classes? [] No, if undefined C++ will define a default constructor [] Yes, without a constructor defined you cannot instantiate a class. " -- Udacity C++ nd213-C3-L2-S17
"No, if undefined C++ will define a default constructor" -- Udacity C++ nd213-C3-L2-S17
"Why does it make sense to specify private member variables with accessor and mutator functions, instead of public member variables? [] It doesn't matter actually, you could just as well make them public. [] Using getter and setter functions is the only way to modify class member variables in C++. [] Often times you want to limit the user's access to class member variables, possibly because of an invariant. " -- Udacity C++ nd213-C3-L2-S17
"Often times you want to limit the user's access to class member variables, possibly because of an invariant." -- Udacity C++ nd213-C3-L2-S17
What is an example a pointer being suitable type, where a reference is not?
"One example is object initialization. You might like one object to store a reference to another object. However, if the other object is not yet available when the first object is created, then the first object will need to use a pointer, not a reference, since a reference cannot be null. The reference could only be initialized once the other object is created." -- Udacity C++ nanodegree
In concurrent programming, what security issues could be caused by using the `detach()` method of standard thread?
"Programmers should be very careful though when using the detach()-method. You have to make sure that the thread does not access any data that might get out of scope or be deleted." -- udacity C++ nd213-C5-L1-S3
What are Prvalues?
"Prvalues do not have an address that is accessible directly. They are temporary expressions used to initialize objects or compute the value of the operand of an operator." -- udacity C++ nd213-C4-L5-S2
"What are the three options for access modifiers in C++? [] Public (access to anyone), Private (access only within the class) and Permitted (access in friend classes) [] Public (access to anyone), Protected (access in friend classes) and Permitted (access only within the class) [] Public (access to anyone), Private (access only within the class) and Protected (access in friend classes) [] Public (access in friend classes), Private (access only within the class) and Protected (access to anyone) " -- Udacity C++ nd213-C3-L2-S17
"Public (access to anyone), Private (access only within the class) and Protected (access in friend classes)" -- Udacity C++ nd213-C3-L2-S17
What does the "Ready suspended" state of a process indicate?
"Ready suspended : A process that was initially in ready state but has been swapped out of main memory and placed onto external storage is said to be in suspend ready state. The process will transition back to ready state whenever it is moved to main memory again" -- udacity C++ nd213-C5-L1-S2
What is Spatial locality?
"Spatial locality means that after an access to an address range, the next access to an address in the immediate vicinity is highly probable (e.g. in arrays). In the course of time, memory addresses that are very close to each other are accessed again multiple times. This can be exploited by moving the adjacent address areas upwards into the next hierarchy level during a memory access." -- Udacity C++ nd213-C4-L2-S4
In memory management, what is Static memory allocation?
"Static memory allocation is performed for static and global variables, which are stored in the BSS and Data segment. Memory for these types of variables is allocated once when your program is run and persists throughout the life of your program." -- Udacity C++ nd213-C4-L3-S2
What is Temporal locality?
"Temporal locality means that address ranges that are accessed are likely to be used again in the near future. In the course of time, the same memory address is accessed relatively frequently (e.g. in a loop). This property can be used at all levels of the memory hierarchy to keep memory areas accessible as quickly as possible." -- Udacity C++ nd213-C4-L2-S4
In lambda functions, what is a capture list?
"The capture list []: By default, variables outside of the enclosing {} around the main part of the Lambda can not be accessed. By adding a variable to the capture list however, it becomes available within the Lambda either as a copy or as a reference. The captured variables become a part of the Lambda." -- udacity C++ nd213-C5-L1-S4
In memory management, what is the heap?
"The heap (also called "free store" in C++) is where data with dynamic storage lives. It is shared among multiple threads in a program, which means that memory management for the heap needs to take concurrency into account. This makes memory allocations in the heap more complicated than stack allocations. In general, managing memory on the heap is more (computationally) expensive for the operating system, which makes it slower than stack memory. Contrary to the stack, the heap is not managed automatically by the system, but by the programmer. If memory is allocated on the heap, it is the programmer's responsibility to free it again when it is no longer needed. If the programmer manages the heap poorly or not at all, there will be trouble." -- Udacity C++ nd213-C4-L3-S1
What does the "Running" state of a process indicate?
"The operating system has selected the process for execution and the instructions within the process are executed on one or more of the available CPU cores." -- udacity C++ nd213-C5-L1-S2
What is a share pointer?
"The shared pointer std::shared_ptr points to a heap resource but does not explicitly own it. There may even be several shared pointers to the same resource, each of which will increase an internal reference count. As soon as this count reaches zero, the resource will automatically be deallocated." -- udacity C++ nd213-C4-L6-S3
How does a smart pointer destructor work?
"The smart pointer destructor contains the call to delete, and because the smart pointer is declared on the stack, its destructor is invoked when the smart pointer goes out of scope, even if an exception is thrown." -- udacity C++ nd213-C4-L6-S3
In memory management, what is the stack?
"The stack is a contiguous memory block with a fixed maximum size. If a program exceeds this size, it will crash. The stack is used for storing automatically allocated variables such as local variables or function parameters. If there are multiple threads in a program, then each thread has its own stack memory. New memory on the stack is allocated when the path of execution enters a scope and freed again once the scope is left. It is important to know that the stack is managed "automatically" by the compiler, which means we do not have to concern ourselves with allocation and deallocation." -- Udacity C++ nd213-C4-L3-S1
What is a unique pointer?
"The unique pointer std::unique_ptr is a smart pointer which exclusively owns a dynamically allocated resource on the heap. There must not be a second unique pointer to the same resource." -- udacity C++ nd213-C4-L6-S3
What is weak pointer?
"The weak pointer std::weak_ptr behaves similar to the shared pointer but does not increase the reference counter." -- udacity C++ nd213-C4-L6-S3
In concurrent programming, how can you avoid having a function complete with out waiting for a thread?
"There are some situations however, where it might make sense to not wait for a thread to finish its work. This can be achieved by "detaching" the thread, by which the internal state variable "joinable" is set to "false". This works by calling the detach() method on the thread." -- udacity C++ nd213-C5-L1-S3
What is the approximate speed comparison of creating thread vs a process?
"These are significantly easier to create and destroy: In many systems the creation of a thread is up to 100 times faster than the creation of a process." -- udacity C++ nd213-C5-L1-S2
In concurrent programming, what is the core problem threads are trying to solve? Tasks?
"Threads and tasks are used for different problems. Threads have more to do with latency. When you have functions that can block (e.g. file input, server connection), threads can avoid the program to be blocked, when e.g. the server is waiting for a response. Tasks on the other hand focus on throughput, where many operations are executed in parallel." -- udacity C++ nd213-C5-L1-S5
In memory management, what is the "Rule of Three"?
"To this end, the Rule of Three states that if a class needs to have an overloaded copy constructor, copy assignment operator, ~or~ destructor, then it must also implement the other two as well to ensure that memory is managed consistently. As we have seen, the copy constructor and copy assignment operator (which are often almost identical) control how the resource gets copied between objects while the destructor manages the resource deletion." -- udacity C++ nd213-C4-L5-S1
In concurrent programming, what are the main advantages of using std::unique_lock<> over std::lock_guard?
"Using std::unique_lock allows you to... 1) ...construct an instance without an associated mutex using the default constructor 2)...construct an instance with an associated mutex while leaving the mutex unlocked at first using the deferred-locking constructor 3)...construct an instance that tries to lock a mutex, but leaves it unlocked if the lock failed using the try-lock constructor 4) ...construct an instance that tries to acquire a lock for either a specified time period or until a specified point in time" -- udacity C++ nd213-C5-L3-S3
What does the "Terminated" state of a process indicate?
"When a process completes its execution or when it is being explicitly killed, it changes to the "terminated" state. The underlying program is no longer executing, but the process remains in the process table as a "zombie process". When it is finally removed from the process table, its lifetime ends." -- udacity C++ nd213-C5-L1-S2
What is an abstract class?
"abstract class: a class that cannot be directly used to create objects; often used to define an interface to derived classes. A class is made abstract by having a pure virtual function or only protected constructors." -- CppCoreGuidelines glossary
"Invoking the const keyword in an accessor function allows you to: a) Require that the data type of the output will be the same as that of the input. b) Ensure the user cannot do anything to change the private attributes of the object. c) Pass in constant attribute values to the accessor function. " -- Udacity C++ nd213-L2-S20
"b) Ensure the user cannot do anything to change the private attributes of the object." -- Udacity C++ nd213-L2-S20
"Making class attributes private and assigning them with a mutator function allows you to: a) Ensure that only class member functions have access to private class attributes. b) Invoke logic that checks whether the input data are valid before setting attributes. c) Prevent users from changing non-public class attributes. " -- Udacity C++ nd213-C3-L2-S20
"b) Invoke logic that checks whether the input data are valid before setting attributes." -- Udacity C++ nd213-C3-L2-S20
What is a pure virtual function?
"pure virtual function: a virtual function that must be overridden in a derived class." -- CppCoreGuidelines glossary
What is a virtual function?
"virtual function: a member function that can be overridden in a derived class." -- CppCoreGuidelines glossary
In C++, what library needs to be included to use `cout`?
#include <iostream>
What are 3 types of smart pointers implemented in C++11?
* unique pointer (`std::unique_ptr`) * shared pointer (`std::shared_ptr`) * weak pointer (`std::weak_ptr`)
In C++, describe storage by reference.
- a reference is an alias to existing memory and is denoted in the type with an `&` - a reference does not store memory itself, it is only an alias to another variable - the alias must be assigned when the variable is initialized (cannot be initialized without a variable)
In C++, describe memory usage for pointers?
- the type of the variable must by modified with `*` - the pointer takes "memory address width" - the pointer "points" to the allocate space of the object.
In what cases are move semantics most relevant?
1) One of the primary areas of application are cases, where heavy-weight objects need to be passed around in a program. 2) A second area of application are cases where ownership needs to be transferred (such as with unique pointers, as we will soon see).
In memory management, what the most common reasons for overloading the `new` and `delete` operators?
1) The overloaded new operator function allows to add additional parameters. Therefore, a class can have multiple overloaded new operator functions. This gives the programmer more flexibility in customizing the memory allocation for objects. 2) Overloaded the new and delete operators provides an easy way to integrate a mechanism similar to garbage collection capabilities (such as in Java), as we will shorty see later in this course. 4) By adding exception handling capabilities into new and delete, the code can be made more robust. It is very easy to add customized behavior, such as overwriting deallocated memory with zeros in order to increase the security of critical application data.
In memory management, what are the most common categories of problems?
1) memory leaks 2) buffer overruns 3) unlimited memory 4) incorrect pairing of allocation and deallocation 5) invalid memory access
In memory management, what the four distinct areas of system memory (for the process memory model) that a C++ will interact with?
1) stack 2) heap 3) BSS (Block Started by Symbol) 4. Data -- Udacity C++ nd213-C4-L3-S1
In memory management, what general types of memory allocation are supported?
1) static memory allocation 2) automatic memory allocation 3) dynamic memory allocation -- Udacity C++ nd213-C4-L3-S2
In C++, when is memory reclaimed?
1. If the object is on the stack, memory is reclaimed when the function returns 2. If the object is on the heap, memory is reclaimed when `delete` is used
In C++, what are the rules for the main function?
1. Must have a global main function 2. The designated start and termination of a program 3. The function cannot be overloaded * it only exists in a single for in the application * it must be either in the basic or extended forms 4. the return type can only be a type of integer 5. A programmer must only return out of main using a return statement (use of `std::exist` leads to undefined behavior)
What are the states for a thread?
1. New 2. Runnable 3. Blocked
In CS, what are the states of OS process?
1. Ready 2. Running 3. Blocked 4. Terminated 5. Ready suspended 6. Blocked suspended -- udacity C++ nd213-C5-L1-S2
In memory management, what are the limitations of `free()`?
1. free can only free memory that was reserved with malloc or calloc. 2. free can only release memory that has not been released before. Releasing the same block of memory twice will result in an error.
In concurrent programming, what is more generic name for `somethread.join()`?
A "thread barrier".
What is "functor"?
A Lambda function object.
In C++, what is custom assignment operator?
A custom assignment operator is: - is a public member function of the class - has the function name operator= - has a return value of a reference of the class' type - has exactly one argument - the argument must be const reference of the class' type
In C++, what is custom copy constructor?
A custom copy constructor is: - a class constructor - has exactly on argument - the argument must be const reference of the same type as the class - Ex: ```cplus Cube::Cube(cosnt Cube & obj) ```
In C++, what is the name for method that releases memory for resources created by a class instance?
A destructor.
In C++, what is .h file.
A header file that defines the interface for class.
In C++, what is a pointer?
A pointer is variable that stores a memory address of the data. Simply put: points are a level of indirection from the data. In C++, a pointer is defined by adding `*` to the type of the variable. Integer Example: ``` cplus int * p = # ```
In CS, what is an invariant?
An "invariant" is a rule that limits the values of member variables.
In C++, what is .ccp file.
An implementation file.
In memory management, what does Bjarne Stroustrup?
Bjarne says `new` and `delete` don't belong in application code. They should be part of the implementation of an abstraction.
In C++, what is the standard starting point (the execution context)?
By convention, a program start execution with the main method, which return and `int`. Syntax: ```cplus int main() { // code goes here } ```
What is common way to discover race conditions while testing software.
By inserting sleep statements, to simulate scheduling anomalies.
In C++, what memory is used by default? Describe the lifecycle of the memory?
C++ uses stack memory by default. Stack memory is associated with the current function and memory's lifecycle is tied to the function (when the function returns the memory is released).
In C++, what is one obvious way to avoid accessing re-allocated memory?
Don't return references to local variables.
In C++, what is encapsulation?
Encapsulation encloses data and functionality in a single unit called (called a class). It also divides members in class into public(can be accessed by client code) and private (cannot be accessed - only used in class itself).
In C++, what stack memory addresses allocated first in a general sense?
High memory addresses are allocated first, subsequently address values decline.
In C++, when will and automatic default constructor be defined?
I any custom constructor is defined, the automatic default constructor is not defined.
In OOP, what is the diamond problem?
If a class inherits from two base classes, both of which themselves inherit from the same abstract class, a conflict can emerge.
In the context of C++, what is heap memory?
If memory needs to exist for longer than the lifecycle of the function, we must use heap memory. The only way to create heap memory in C++ is with the `new` operator. The new operator returns a pointer to the memory storing the data - not an instance of the data itself.
What is the meaning of the `*` when it appears on the right side of the equation?
If the `*` appears on the right hand side of an equation or in front of an already-defined variable, the meaning is different. In this case, it is called the "dereferencing operator", and it returns the object being pointed to.
What is a potential downside to having to objects with member variables pointing to the same data?
If the object destructor, releases the member variable date from memory, then one object being destroyed will cause the remaining object to raise an error.
In C++, what is the name for the variable y declare as follows: ```cplus int &y = new x*; ```
In this example `y` is a reference variable.
In C++, what does the following syntax (ampersand in front of variable) do? ```cplus int a = &b; ```
It assign the memory address of b to a.
In C++, how can an instance of variable be stored?
It can be stored directly in memory, accessed by pointer, or accessed by reference.
What does `std::future.get()`do?
It get the result returned by the promise, and blocks execution it has that value. If the result is movable (which is the case for std::string), it will be moved - otherwise it will be copied instead.
In C++, what does the automatic default destructor do?
It is added to the class if no other destructor is defined. The only action of the automatic default destructor is to call the default destructor for all member objects.
What does Mutex stand for?
MUtual EXclustion
Can you declare smart pointers outside of the stack?
No, smart pointers always need to be declared on the stack, otherwise the scoping mechanism would not work.
In C++, when is copy constructor invocated?
Often, copy constructors are invocated automatically: - passing an object as a parameter (by value) - returning an object from a function (by value) - initializing a new object
With regards to pointers and references, can they be declared without being initialized?
Pointers can be declared without being initialized, but references must be initialized when they are declared.
With regards to pointers and references, can they be set to null?
References can not be null. This means that a reference should point to meaningful data in the program. Pointers can be null. In fact, if a pointer is not initialized immediately, it is often best practice to initialize to nullptr, a special type which indicates that the pointer is null.
What is `std::auto_ptr`?
Something that's effectively deprecated.
In memory management, what the six distinct areas of system memory (for the process memory model)?
The 6 areas are: 1) OS Kernel Space 2) Stack 3) Heap 4) BSS (Block Started by Symbol) 5) Data 6) Text -- Udacity C++ nd213-C4-L3-S1
In C++, is the syntax `nullptr`?
The C++ keyword nullptr is pointer that points to the memory address 0x0. 0x0 is reserved and never used by the system. Accessing 0x0 will always cause a seg fault. Calls to delete 0x0 are ignored.
In C++, describe the new operator.
The `new` operator in C++ will always do three things: 1. allocate memory on the heap for the data structure 2. initialize the data structure 3. return the pointer to the start of the data structure The memory is only ever reclaimed by the system when the pointer is passed to the delete operator.
In C++, what will the following code print? ```cplus auto i = 1; auto c = i++; cout << "The value of c is: " << c << "\n"; cout << "The value of i is: " << i << "\n"; cout << "\n"; ```
The code will return: ``` The value of c is: 1 The value of i is: 2 ```
In C++, what will the following code print? ```cplus auto i = 1; c = ++i; cout << "The value of c is: " << c << "\n"; cout << "The value of i is: " << i << "\n"; cout << "\n"; ```
The code will return: ``` The value of c is: 2 The value of i is: 2 ```
In C++, what is pointer dereference operator?
The dereference operator removes the indirection. The `*` operator should precede the pointer being dereferenced. EX: ```cplus int num = 7; int * p = # int value_in_num = *p; *p = 42; ```
In concurrent programming, what will happen if you comment out `somethread.join()` in working program?
The program will crash by design, to make it clear to the developer that this not the right way of using the thread API.
What is the scope resolution operator?
The scope resolution operator `::` is used to identify and disambiguate identifiers used in different scopes.
In C++, what is a Custom Default Constructor?
The simplest constructor is the custom default constructor. We define it by creating: - a member function with the same name as the class - the function takes zero parameters - the function does not have a return type
In memory management, what function can be used to change the amount of memory previously allocated? What is the syntax?
The size of the memory area reserved with malloc or calloc can be increased or decreased with the realloc function. ```cplus pointer_name = (cast-type*) realloc( (cast-type*)old_memblock, new_size ); ```
In C++, how are variables store by default?
They are stored in stack memory, and object takes up exactly its size in memory. This happens when the type of variable has no modifiers.
In C++, according to the Google style guide, what is the naming convention for private member variables?
They should start with and underscore (_).
In C++, how a custom destructor implemented?
To add custom behavior to the end-of-life of the function, a custom destructor can defined as: - a custom destructor is member function - the function's destructor is the name of the class, preceded by a tilde ~ - all destructors have zero arguments and no return type - EX syntax: `Cube::~Cube();`
In C++, what is a vector?
Vectors are defined in the STL, using `std::vector` class. This class provides functionality of a dynamically growing array with a "templated" type.
In C++ what is the arrow operator?
When an object is stored via a pointer, access can be made to the member functions using the -> operatator. EX: ```cplus c->getVolume(); # identical to (c*).getVolume(); ```
Can class member variables be declared as `const`?
Yes, but only if the member variable is initialized through an initialization list. -- Udacity C++ nd213-C3-L2-S12
In C++, to read a file, what must you include and what is the type of a file object?
You must use `#include <fstream>` and `std::ifstream`?
In C++, why is `#include <iostream>` not followed by a semicolon?
`#include <iostream>` is pre-processor command. It is not compiled, so it does not require a semicolon.
What needs to be included to use separate thread of execution?
`#include <thread>`
When compiling code that uses threads with `g++`, what flag must be used?
`-pthread`
What is the name for the `::` in C++?
`::` is the scope resolution operator.
In concurrent programming with C++, what is the syntax for getting current thread ID?
``` #include <thread> int main() { std::cout << "Hello concurrent world from main! Thread id = " << std::this_thread::get_id() << std::endl; } ``` -- udacity C++ nd213-C5-L1-S3
In C++, what will be printed by the following code? ```cplus int MultiplyByTwo(int &i) { i = 2*i; return i; } int main() { int a = 5; cout << "The int a equals: " << a << "\n"; int b = MultiplyByTwo(a); cout << "The int b equals: " << b << "\n"; cout << "The int a now equals: " << a << "\n"; } ```
``` The int a equals: 5 The int b equals: 10 The int a now equals: 10 ```
In C++, what will be printed by the following code? ```cplus int MultiplyByTwo(int i) { i = 2*i; return i; } int main() { int a = 5; cout << "The int a equals: " << a << "\n"; int b = MultiplyByTwo(a); cout << "The int b equals: " << b << "\n"; cout << "The int a equals: " << a << "\n"; } ```
``` The int a equals: 5 The int b equals: 10 The int a still equals: 5 ```
In C++ what is the syntax for defining an integer poiter?
``` cplus int * p = # ```
In C++, how do you execute a program (using a make file)?
```bash cd path/to/code make ./main ```
In C++, for the vector of integers stored in`a`, how would pop (remove and store) the element with the highest index?
```cout auto val = a.back(); a.pop_back(); ``` SEE: https://stackoverflow.com/a/40500849
In C++, what is syntax for telling the compiler to define the header file header_example.h only if it has not already been defined?
```cplus #ifndef HEADER_EXAMPLE_H #define HEADER_EXAMPLE_H #endif ```
In C++, how do you include the header_example.h header file?
```cplus #include "header_example.h" ```
What includes are necessary, for handling promises?
```cplus #include <future> ```
What is the syntax for writing "Hello world" from a separate thread?!
```cplus #include <iostream> #include <thread> void threadFunction() { std::cout << "Hello world!\n"; } int main() { // create thread std::thread t(threadFunction); // allow thread to complete before executing t.join(); // do something in main() return 0; } ```
What is the syntax (with #include) for creating a unique pointer to an integer and assigning it the value 2?
```cplus #include <memory> int main() { std::unique_ptr<int> unique(new int); // create a unique pointer on the stack *unique = 2; // assign a value } ```
What is the template syntax (with `#include`) for creating a unique pointer object?
```cplus #include <memory> std::unique_ptr<Type> p(new Type); ```
In C++, what are include and using statements for string streaming?
```cplus #include <sstream> using std:istringstream; ```
In C++, what must appear at the top of a header file?
```cplus #pragma once ```
In concurrent programming, what is the syntax for creating a promise, passing it into a thread, an retrieving the value?
```cplus // create promise and future std::promise<std::string> prms; std::future<std::string> ftr = prms.get_future(); // start thread and pass promise as argument std::thread t(modifyMessage, std::move(prms), messageToThread); // print original message to console std::cout << "Original message from main(): " << messageToThread << std::endl; // retrieve modified message via future and print to console std::string messageFromThread = ftr.get(); ```
In C++ syntax, if the Cube class uses the following constructor. What is the syntax for the custom copy constructor? ```cplus Cube::Cube() { length_ = 1; } ```
```cplus Cube::Cube(const Cube & obj) { length_ = obj.lenght_; } ```
In C++, what is the syntax for declaring a class?
```cplus class Cube { public: // public protection region double getVal(); void setLength(double length); private: //private protection region double length_; };
In memory management, what is syntax for implementing a "no copy" copy-ownership policy?
```cplus class NoCopyClass2 { public: NoCopyClass2(){} NoCopyClass2(const NoCopyClass2 &) = delete; NoCopyClass2 &operator=(const NoCopyClass2 &) = delete; }; ```
What is the syntax for simply printing the address of the variable `i`?
```cplus cout << "The address of i is: " << &i << "\n"; ```
What is the syntax for printing the first element the vector pointed to by the `pointer_to_v`?
```cplus cout << "The first element of v is: " << (*pointer_to_v)[0] << "\n"; ```
What is the syntax for printing the value pointed to by `pointer_to_i`?
```cplus cout << "The value of the variable pointed to by pointer_to_i is: " << *pointer_to_i << "\n"; ```
In C++, what is the syntax for creating color enum, that includes colors from the US flag?
```cplus enum class Color {red, white, blue}; ```
In C++, what is the syntax for printing numbers 1 through 4?
```cplus for (int i=0; i < 5; i++) { cout << i << "\n"; } ```
In C++ syntax, how do you create a modern range-based for loop? How is the data copied from the container?
```cplus for (int x : int_list) { // This version of the loop makes a temporary copy of each // list item by value. Since x is a temporary copy, // any changes to x do not modify the actual container. x = 99; } ```
In C++ syntax, how do you create modern range-based for loop by reference?
```cplus for (int& x : int_list) { // This version of the loop will modify each item directly, by reference! x = 99; } ```
In C++ syntax, how is "to string" implemented?
```cplus friend std::ostream& operator <<(std::ostream & os, const Stack & stack); ```
In C++, what is the syntax for writing out whether `number` is positive negative or 0.
```cplus if (number > 0) { cout << "You entered a positive integer: " << number << endl; } else if (number < 0) { cout << "You entered a negative integer: " << number << endl; } else { cout << "You entered 0." << endl; } ```
What is the syntax for allocating heap memory for 3 ints, assigning 3 int values?
```cplus int *p = (int*)malloc(3*sizeof(int)); p[0] = 1; p[1] = 2; p[2] = 3; printf("address=%p, second value=%d\n", p, p[1]); ```
In C++, what is the extended form of the `main` function?
```cplus int main(int argc, char* argv[]) { // do stuff } ```
In C++, what is the compact sytax for printing ever letter in the `my_stream` variable (`istringstream`) to a seperate line and printing "DONE" at the end of the stream.
```cplus int n; while (my_stream >> n) { cout << n << "\n"; } cout << "DONE" << "\n"; ```
In C++, what is the syntax for a fuction that sums all elements in vector `v`?
```cplus int sum() { int result = 0; for(auto n: vec) { result += n; } return result; }
What is the syntax for storing the address of variable `i` (`int`)?
```cplus int* pointr_to_i = &i; ```
In concurrent programming, what is the syntax for creating a task?
```cplus std::future<double> ftr = std::async(divideByNumber, num, denom); ```
In concurrent programming, what is the syntax for creating a task that can be run in parallel or in serial?
```cplus std::future<double> ftr = std::async(std::launch::async | std::launch::deferred, divideByNumber, num, denom); ```
In C++, what is the sytnax for printing every line in a file?
```cplus std::ifstream my_file; my_file.open("path/to/file.txt"); if (my_file) { std:string line; while (getline(my_file, line)) { std::cout << line << "\n"; } } ```
What is the syntax for creating a shared pointer?
```cplus std::shared_ptr<int> shared1(new int); ```
In concurrent programming, what is the syntax for sleeping the current thread for 10 milliseconds.
```cplus std::this_thread::sleep_for(std::chrono::milliseconds(i)); ```
When using threads, what are the 3 ways to initialize a thread using the (callable) `Vehicle` class?
```cplus std::thread t1( (Vehicle()) ); std::thread t2 = std::thread( Vehicle() ); std::thread t3{ Vehicle() }; ```
What is the syntax for defining a struct that holds an `int`, `double`, and `char[5]. And creating instance of that `struct` which stores it's memory on the heap? And assigning values to members of s`struct`.
```cplus struct MyStruct { int i; double d; char a[5]; }; MyStruct *p = (MyStruct*)calloc(1,sizeof(MyStruct)); p[0].i = 1; p[0].d = 3.14159; p[0].a[0] = 'a'; ```
What is the syntax for defining a constructor for a `Date` class outside of the class definition?
```cpp Date::Date() {} ```
In C++, how could you create `Hello()` functions for Spanish and English using namespaces (syntax)?
```cpp namespace English { void Hello() { std::cout << "Hello, World!\n"; } } // namespace English namespace Spanish { void Hello() { std::cout << "Hola, Mundo!\n"; } } // namespace Spanish ```
Many tutorials for `rvalues` actually provide info for what value category?
`prvalues`
In C++, what is the syntax for aliasing the `celsius_to_farenheit` function to `c2f`?
`using c2f = celsius_to_farenheit;`
"In the context of object oriented programming, encapsulation refers to: a) A requirement that data and logic be packaged separately in distinct objects b) The notion that data and logic can be packaged together and passed around within a program as a single object. c) The restriction that logic within a particular object can only operate on data stored within that same object. " -- Udacity C++ nd213-C3-L2-S20
b) "The notion that data and logic can be packaged together and passed around within a program as a single object." -- Udacity C++ nd213-C3-L2-S20
When people refer to modern C++, what minimum version are they typically referring to?
c++ 11
What does the calloc do?
calloc (short for Cleared Memory Allocation) is used to dynamically allocate the specified number of blocks of memory of the specified type. It initializes each block with a default value '0' ```cplus pointer_name = (cast-type*) calloc(num_elems, size_elem); ```
In memory management, what are the five categories of values?
categories of values - gvalue - rvalue - lvalue - xvalue - prvalue
In C++, how is vector defined, initialized, what is the method for adding the (back) of array, how specific element accessed, how to get the number of elements.
defined in: `#include <vector>` initialization: `std::vector<T> v; add to: `::push_back(T)` access specific element: `::operator[](unsigned pos)` number of elements: `::size()`
In C++, what are the six common primitive types ?
int - integers char - single characters bool - boolean float - floating point number double - double-precision floating point number void - denotes
What does the malloc function do?
malloc (short for Memory Allocation) is used to dynamically allocate a single large block of memory with the specified size. It returns a pointer of type void which can be cast into a pointer of any form. The syntax is as follows: ``` cplus pointer_name = (cast-type*) malloc(size); ```
In C++, according to reddit what references are discouraged?
only cplusplus.com the following have been upgraded: w3schools learncpp SEE: https://www.reddit.com/r/learnprogramming/wiki/index#wiki_discouraged_resources
In memory management, what is a modern alternative to implementing your own copy-ownership policy code?
smart pointers
In C++, what are the most common user-defined types?
std::string - string or sequence of characters std::vector - a dynamically-growing array