C++ Programming
What is the "this" keyword?
"this" is a pointer to the current object instance. In a const function, "this" will act as a const pointer.
Pointer Arithmetic Given int* ptr = ..., how many bytes over will (ptr + 2) go? What about ((char*)ptr + 2)
8 bytes (4 bytes in an int * 2). The pointer type will determine how many bytes over in memory the pointer goes. The second line will go over 2 bytes since char's are 1 byte.
How does a 2D array compare to a 1D array in terms of memory performance?
A 2D array is an array of arrays. Each of those arrays may not be located near each other in memory, leading to more cache misses.
What is a class and object in C++?
A class is a user-defined data type. Classes can contain member variables and functions. Objects are instances of classes and can be thought of as variables of a class type.
What is a cold cache? What is a hot cache? What is cache warming?
A cold cache is an empty cache. A hot cache is a cache with relevant data that we will use. Cache warming is artificially filling a cache with data to warm it up.
What is #include?
A preprocessor command that copies code from another file into the current file.
What is weak_ptr?
A smart pointer that when assigned to a shared_ptr does not increase the reference count.
What's wrong with this function: int* CreateArray() { int array[50]; return array; }
Array is created on the stack so when the function finishes, array will be deallocated. So, CreateArray() will return a pointer pointing to deallocated memory. Solution: One solution is to use new and allocate the array on the heap.
What are different ways to initialize an array?
Arrays can be initialized using {} and filling in the elements of the array. Memset takes 3 parameters: a pointer, a value, and an integer representing the size of the array. It will fill the memory addresses starting at the pointer and going out size bytes with the specified value.
Arrays vs linked lists?
Arrays: Access in O(1) time. Adding and removing from the middle requires copying and shifting the elements in the array. Contiguous blocks in memory, meaning more cache hits when doing some operation on multiple elements of the array. Linked list: Access in O(n) time. Adding and removing does not require copying or shifting elements. Requires more memory since each element needs a pointer to the next node. Not contiguous block in memory, which could be more efficient memory storage (since nodes can be stored anywhere).
How can you append two strings? #include <string> A. std::string str1 = "hi " + "how are you"; B. std::string str1 = std::string("hi ") + "how are you"; C. std::string str1 = "hi "; str1 += "how are you";
B and C work. += is an overloaded operator in string. A attempts to add two const char arrays which does not work.
Are strings just pointers to char arrays?
Basically. A string is a pointer to a const char array which ends in a null termination character ('\0').
What is the difference between static and global?
Both are not allocated on the stack. Static variables may not have global scope.
What is the difference between C and C++?
C++ is object-oriented while C is procedure-oriented. C++ is a superset of C. Provides data encapsulation, function overloading, and namespace. Uses new and delete (in addition to malloc and free).
What is the difference between C-style and C++-style casts?
C-style casts are written using (type). Ex: int a = 10; double b = (double) a; C++-style casts are static_cast, dynamic_cast, const_cast, and reinterpret_cast.
What is an inline function?
If a function is defined as inline, the compiler copies the code of the function at each point where the function is called at compile time. This eliminates the overhead of calling a function.
How big is an int? Float? Double? Bool? Char?
Int: 4 bytes Float: 4 bytes Double: 8 bytes Bool: 1 byte Char: 1 byte
What does the linker do?
It links all of the object files into a single executable.
What are namespaces?
Namespaces provide a method for explicitly defining scope to identifiers within it. They are defined using namespace identifier { named entities } They can be accessed by prefixing XXX :: or keyword using namespace XXX Namespaces should never be used in a header file
What are C++ access specifiers?
Public: Can be accessed outside of the class. Private: Cannot be accessed outside of the class. Protected: Can be accessed by the class and the derived class.
What is the difference between shallow copy and deep copy?
Shallow copy stores the references of objects to the original memory address. Shallow copy is faster. Shallow copy reflects changes made to the copied object in the original. Deep copy makes a new copy of each object with their own memory addresses. Deep copy is slower. Deep copy doesn't reflect changes made to the copied object in the original.
Why would you mark a member function as const?
So const object could call that function.
What is the following syntax mean: class A { int X; int GetX() const { return X }; }
The const at the end of GetX() means that GetX() will not modify any member variables. This syntax only works inside of a class.
Say Class A is a parent for Class B. When an instance of B is created, in what order are the constructors called? In what order are the destructors called?
The constructor for A is called first and then the constructor for B. The destructor for B is called before the destructor for A.
What is explicit?
The explicit keyword can be placed in front of a constructor to prevent implicit conversion. class Entity { public: explicit Entity(int age) {} } prevents this from working: Entity e = 22;
What is the difference between a struct and a class in C++?
The functions and member variables default to public in a struct and private in a class. When deriving from a struct, the default access specifiers for the base struct are public. When deriving from a class, the default access specifiers for the base class are private.
What is main?
The main function is the entry point for a program.
What happens if you mark a class member as mutable?
The mutable variable can be modified in a const function.
How can you allocate and deallocate memory in C++?
Using new and delete.
What is vector? How do you create one? How do you add to one? How do you get its size? How do you remove the second element? How do you set the vector capacity to 3?
Vector is a class in the STL. It is essentially a dynamic array. Vectors are stored on the heap. std::vector<int> intVec; intVec.push_back(1); intVec.size(); intVec.erase(vertices.begin() + 1); intVec.reserve(3);
What is the difference between const int*, int const*, int* const?
const int* is a pointer to an int that is a constant. int const* is a pointer to a const int. (i.e. these are equivalent). int* const is a const pointer to an int. Note: Read it in reverse. const int* is a pointer to a constant int. int* const is a constant pointer to an integer.
How do you delete b? int* b = new int[50];
delete[] b When you use new with square brackets, you must use delete with square brackets.
How do you find the size of an array on the stack? Does this method work for the heap?
int arr[5]; int size = sizeof(arr) / sizeof(arr[0]) This does not work for arrays on the heap.
What is memcpy?
memcpy(pointer1, pointer2, numBytes) copies numBytes bytes from pointer2's memory location to pointer1's.
What are some features of C++11?
nullptr Different types of chars (wchar_t, char16_t, char32_t) Lambda expressions
Given: vector<Vector3> vec; What is the difference between vec.push_back(Vector3(0, 0, 0)) and vec.emplace_back(0, 0, 0)?
push_back adds a copy of the Vector3 object to the vector. emplace_back creates a Vector3 object in-place in the vector and initializes it with the passed in values.
What are the principles of object-oriented programming?
Encapsulation, abstraction, inheritance, and polymorphism. Encapsulation: hiding data implementation by restricting access to public methods. Instance variables are kept private and public methods are used to access them. Abstraction: The concept of knowing only the interface (or essential info) of a class and keeping its implementation hidden. Inheritance: Expressing "is-a" and/or "has-a" relationships between two objects via deriving from a class or implementing an interface. Polymorphism: Function overloading
Describe the virtual keyword. What are the vtable and vpointer?
In C++, virtual is the main mechanism for runtime polymorphism. Typically, when a function is called on an object the reference/pointer type is used to determine which function is called. When a function is defined as virtual in a base class, at runtime the object type is used to determine which function is called instead of the reference/pointer type.
What is a friend class and friend function?
A class which defines a friend class or friend function grants that class or function access to its private, protected, and public members. Friend functions are not member functions. Friend is not transitive or inherited.
What is a string literal? How long is their lifetime?
A const char array ending in a null termination character ('\0'). Their lifetime is the lifetime of the program.
What is a constructor and what are its properties?
A constructor is function that is automatically run when an instance of a class is created. A default constructor is generated for a class if no constructor is created by the user. A constructor has the same name as the class and no return type. Fun fact: You can hide the constructor by making it private or remove the constructor by setting it equal to delete: Class Entity { Entity() = delete; }
What is the free list?
A data structure for dynamic memory allocation. Operates by connecting the regions of unallocated heap memory into a linked list.
What is a destructor and what are its properties? Can it be virtual? Can it be overloaded?
A destructor is a function that is automatically run when an object is destroyed. It cannot be overloaded since it has not parameters. It can be virtual. A virtual destructor is useful when a derived class deals with dynamically allocated memory that its base class does not, and so it needs specific behaviors for when it is destroyed. Destructors should be used to free any manually allocated memory.
What is extern?
A keyword that tells the compiler to look for the variable in an external translation unit (.cpp file).
What is a copy constructor?
A member function that initializes an object using another object of the same class. By default, the compiler provides a default copy constructor which uses shallow copy. It needs to be overriden if the class uses pointers or runtime memory allocation. A copy constructor may be called when an object is returned by value, an object is passed to a function by value, when an object is constructed using another object of the same class, or when the compiler creates a temporary variable.
What is a wild pointer?
A pointer that is not initialized to any valid address or NULL is considered as wild pointer. Consider the following code fragment - int *p; *p = 20; Here p is not initialized to any valid address and still we are trying to access the address. The p will get any garbage location and the next statement will corrupt that memory location.
What is a void pointer?
A pointer with no data type associated with it. It can hold addresses of any type. A pointer of any type can be assigned to a void pointer but the opposite requires a typecast. void* ptr; char* charPtr; ptr = charPtr; // This is fine charPtr = (char*)ptr; // This requires cast Void pointers cannot be dereferenced. You cannot perform pointer arithmetic on void pointers.
What is a reference? What is a pointer? What is the difference between the two?
A reference is an alias for a variable. A pointer holds the memory address of another variable and needs to be dereferenced to access the value of what it points to. Both hold memory addresses. References cannot be reassigned and only provide one level of indirection. References cannot be set to null. References must be assigned when they are created. References share the same memory location as the variable they reference. Pointers can be reassigned and can provide multiple levels of indirection (you can have pointers to pointers). Pointers can equal null. Pointers have their own memory location.
What is the standard template library?
A set of template classes that provide common data structures and functions including vectors, lists, stacks, queues, sets, and maps.
What is a singleton?
A singleton class is a design pattern that only allows a single instanciated instance of a class. You do this by making the constructor private and having a static method that ""getInstance"" that will be a pointer to a local copy. NOTE, in general it's NOT thread safe.
What is shared_ptr?
A smart pointer (like unique_ptr) except that it maintains a reference count that keeps track of the number of references to the pointer. When the reference count hits zero, the pointer and memory it points to are freed. std::shared_ptr<Entity> entity = std::make_shared<Entity>(); This works: std::shared_ptr<Entity> entity2 = entity;
What is unique_ptr?
A smart pointer that deletes what it's pointing to when the pointer is destroyed. std::unique_ptr<Entity> entity = std::make_unique<Entity>(); Note: unique_ptrs cannot be copied. This doesn't work: std::unique_ptr<Entity> entity2 = entity;
How do you know where a string ends in memory?
A string ends in a null termination character ('\0').
What is a pure virtual function.
A virtual function whose implementation is not provided. The syntax is as follows: virtual void func() = 0;
What is an abstract class? How do you declare an abstract class?
An abstract class is a class that cannot be instantiated and exists to be a parent for other classes. A class is abstract if it has a pure virtual function.
What is a static array?
An array whose size does not change. C++11 provides the std::array which is a static array. Static arrays are stored on the stack. To create a standard array, you need to specify the array type and size: std::array<int, 5> myArray; C++11 provides a dynamic array which is vector.
What is an enum?
An enum is an enumerated data type which means each enum will be assigned an integer number that corresponds to it
What is a tuple?
An object that can hold a number of values of different types. You can create them like this: std::tuple<int, char> myTuple; You can set their values like this: myTuple = std::make_tuple(0, 'a'); You can access and modify specific elements like this: std::get<0>(myTuple) = 1; or myTuple.first = 1
What is static?
In a class, a static member variable has only one version of itself maintained for the entire class. They can be accessed directly through the class using the scope resolution operator instead of through an object. Static member functions can also be accessed similarly and can only use static member variables and other static functions. In a function, a static variable is allocated for the lifetime of the program. Even if a function is called multiple times, the same version of the variable will persist through each call. Outside of any classes or functions, a static variable or function will only be seen by the translation unit it is in. The linker will not see the variable/function when linking files.
Why would you allocate on the stack/heap?
In general, you should try to allocate on the stack because it's much faster. Stack allocation lasts as long as its function scope, so if you need your data to last longer than the function scope, you should allocate on the heap. In addition, if you need more memory than is available on the stack then you should use the heap. Heap memory can grow while stack memory has a set size.
What does the -> (arrow) operator do?
It can be used to call functions on pointers: Entity* entity = new Entity(); entity->function(); It dereferences the pointer and calls the function. Equivalent to: (*entity).function();
What is a dangling pointer?
a pointer that contains the address of a heap-dynamic variable that has been deallocated. Solve this by setting the pointer to NULL.
What is #pragma once?
It makes sure the current file is only included once whenever it is included using #include. This is known as a header guard.
What does the compiler do?
It takes the .h and .cpp files and translates them into .o or .obj files (object files).
What is the difference between new and malloc?
New calls constructors while malloc doesn't. New returns an exact type while malloc returns a void pointer. The amount of memory required is calculated by the compiler for new but must be specified in malloc. On failure, malloc returns null while new throws an exception.
What is "new"?
New is an operator used to allocate memory on the heap.
Are strings mutable?
No, strings are immutable.
Can virtual functions be static?
No, the object type is used to determine which function is run for a virtual function and static functions are not run on objects.
What is a null pointer? What is nullptr?
Null pointer is a pointer pointing to nothing (null). Nullptr is a value (an integer literal that evaluates to 0).
What is operator overloading?
Operator overloading is defining the behavior of operators (like +, -, *, /, <=, ==, etc.) for user-defined data types. Operators are just functions. To overload + for the Vector3 function you could do this: Vector3 operator+(Vector3 a, Vector3 b) {...}
When would you pass by value vs. pass by reference?
Passing by value involves copying the values being passed to the function into the stack. Any changes to the values in the function will not persist outside of the function. Passing by reference means passing the memory address of the variables to the function. Changes to variables that are passed by reference will persist outside of the function.
Explain polymorphism in C++.
Polymorphism is the ability for a function to have multiple kinds of behavior. There are two types of polymorphism: compile-time and runtime. Compile-time polymorphism is achieved through function overloading and operator overloading. It is fast because it is known at compile-time and resolved by the compiler. Runtime polymorphism is achieved through virtual functions and function overriding. It is slower than compile-time polymorphism.
What is ::
Scope resolution operator.
From the STL: What is a array deque queue priority_queue stack set map unordered_set unordered_map
Standard array (includes bounds checking, keeps track of array size) #include <array> std::array<int, 5> array; array.size(); Double-ended queue (Deque), not contiguous memory, faster insertion to the front than vectors Queue - underlying container is deque or list Priority queue - greatest element at the top Stack - underlying container is vector or deque Set - ordered from least to greatest, implemented via BST Map - keys are ordered, implemented via BST Unordered set - hash table Unordered map - hash map
What kind of memory are string literals stored?
String literals are stored in a readonly area of memory.
Stack vs heap memory? (Mention allocation and deallocation)
The stack and heap are both located in RAM. Heap allocation is done using new. When we allocate memory on the stack, the stack pointer simply shifts down the number of bytes that we allocate (this is very fast). Heap allocation requires much more overhead (involves checking the free list for memory). Stack memory is automatically deallocated. Heap memory must be manually deallocated using delete. If you don't deallocate heap memory, you will have memory leaks (chunks of inaccessible memory).\ The heap is much larger than the stack so if you need a large chunk of memory, you may have to use the heap. Note: each thread will have its own stack but all threads share heap memory.
What is the purpose of a header file?
To contain declarations of variables and functions.
What is stack overflow?
When a program starts, the OS allocates some amount of reserved space for the program's call stack. If the call stack grows beyond the reserved space during execution, stack overflow has occurred and the program crashes. Infinite recursion can lead to stack overflow.
What is a memory leak?
When we lose access to dynamically allocated memory so we can't use or free it. This can happen when the pointer to the memory is deallocated (for example, by going out of scope).
Is this syntax valid? class Entity { private: int m_Num; string m_Str; public: Entity() : m_Num(0), m_Str("Hi") {} }
Yes, this is an example of a member initializer list. m_Num is set to 0 and m_Str is set to "Hi" in the constructor.
What is a template?
You can define a template so that a function or class can take in any kind of type for its parameters. Defining a template will tell the compiler how to create a version of that function or class for any given parameter type. Templates, in a sense, provide automatic class and function overloading.
What is static_cast? What is dynamic_cast? What is const_cast?
static_cast: Compile-time cast. Performs implicit and explicit conversions between types. Performs type checking. Casting a derived class to its base class only works if the inheritance is public. dynamic_cast: Runtime cast. Primarily used for downcasting. Base class must be polymorphic in order to dynamic_cast (must contain a virtual function). If the cast does not work, it will return a null pointer. const_cast: Used to cast a const variable to a not-const or vice versa.