Advanced C++ Flashcards
Assertion
auto
- A keyword indicating that a variable gets its type from its initializer.
- Can be used in place of the return type of function, but in this case the function must have a trailing return type
What is catch (…)?
Default exception
Class Template
Closure
- An unnamed function object that stores the said function’s environment.
- A runtime object created by a lambda expression.
What is the Const Data?
- The const data area stores string literals and other data whose values are known at compile time. No objects of class type can exist in this area. All data in this area is available during the entire lifetime of the program.
- Further, all of this data is read-only, and the results of trying to modify it are undefined. This is in part because even the underlying storage format is subject to arbitrary optimization by the implementation. For example, a particular compiler may store string literals in overlapping objects if it wants to.
Const Member Function
- Declaring a member function with the const keyword specifies that the function is a “read-only” function that does not modify the object for which it is called. A constant member function cannot modify any non-static data members or call any member functions that aren’t constant.
- To declare a constant member function, place the const keyword after the closing parenthesis of the argument list. The const keyword is required in both the declaration and the definition.
**class** **Date** { public: Date( int mn, int dy, int yr ); int getMonth() **const**; *// A read-only function*void setMonth( int mn ); *// A write function; can't be const*private:int month; }; int Date::getMonth() **const** { **return** month; *// Doesn't modify anything* } void Date::setMonth( int mn ) { month = mn; *// Modifies data member* } int main() { Date MyDate( 7, 4, 1998 ); **const** Date BirthDate( 1, 18, 1953 ); MyDate.setMonth( 4 ); *// Okay* BirthDate.getMonth(); *// Okay* BirthDate.setMonth( 4 ); *// C2662 Error* }
decltype
- For deducing data-type from expression, or an auto variable.
declval
- Converts any type T to a reference type, making it possible to use member functions in decltype expressions without the need to go through constructors.
- Commonly used in templates where acceptable template parameters may have no constructor in common, but have the same member function whose return type is needed. Note that because no definition exists for declval, it can only be used in unevaluated contexts; it is an error to evaluate an expression that contains this function.
What is delete[]?
Deallocate storage space of array
#include *// std::cout***struct** MyClass { MyClass() {std::cout \<\<"MyClass constructed**\n**";} ~MyClass() {std::cout \<\<"MyClass destroyed**\n**";} }; void main () { MyClass\* pt = **new** MyClass[3]; **delete**[] pt; }
Derived Classes
- Runtime polymorphism, in C++, is provided by deriving classes from a base class that contains virtual functions.
- The base class and virtual functions form the polymorphic prototype.
- Code written to accept the base class that calls these virtual functions will accept any class instance derived from the base class.
Explain how C++ dynamic memory works
Exception Handling
<small><span style="color: #BC7A00;">#include </span> <span style="color: #008000; font-weight: bold;">using</span> <span style="color: #008000; font-weight: bold;">namespace</span> std; <span style="color: #B00040;">int</span> <span style="color: #0000FF;">main</span> () { try { <span style="color: #008000; font-weight: bold;">throw</span> <span style="color: #666666;">20</span>; } <span style="color: #008000; font-weight: bold;">catch</span> (<span style="color: #B00040;">int</span> e) { cout <span style="color: #666666;"><<</span> <span style="color: #BA2121;">"An exception occurred. Exception Nr. "</span> <span style="color: #666666;"><<</span> e <span style="color: #666666;"><<</span> <span style="color: #BA2121;">'\n'</span>; } <span style="color: #008000; font-weight: bold;">return</span> <span style="color: #666666;">0</span>; } </small>
Nested Exception Handling
try { try { **throw** std::runtime\_error("Test"); } **catch** (std::runtime\_error& e) { std::cerr \<\< "Inner Exception-Handler: " \<\< e.what() \<\< std::endl; **throw**; } } **catch** (std::exception& e) { std::cerr \<\< "Outer Exception-Handler: " \<\< e.what() \<\< std::endl; }
Will result in:
Inner Exception-Handler: Test Outer Exception-Handler: Test
What is the purpose of the explicit keyword?
- To tell the compiler that a certain constructor may not be used to implicitly cast an expression to its class type.
- The explicit keyword is an optional decoration for constructors that take exactly one argument. It only applies to single-argument constructors since those are the only constructors that can be used in type casting.
For example, without the explicit keyword the following code is valid:
**class** **Foo** { public: Foo(int x); }; **class** **Bar** { public: Bar(double x); }; void yourCode() { Foo a = 42; *//OK: calls Foo::Foo(int) passing 42 as an argument* Foo b(42); *//OK: calls Foo::Foo(int) passing 42 as an argument* Foo c = Foo(42); *//OK: calls Foo::Foo(int) passing 42 as an argument* Foo d = (Foo)42; *//OK: calls Foo::Foo(int) passing 42 as an argument* Bar x = 3.14; *//OK: calls Bar::Bar(double) passing 3.14 as an argument* Bar y(3.14); *//OK: calls Bar::Bar(double) passing 3.14 as an argument* Bar z = Bar(3.14); *//OK: calls Bar::Bar(double) passing 3.14 as an argument* Bar w = (Bar)3.14; *//OK: calls Bar::Bar(double) passing 3.14 as an argument* }
But sometimes you want to prevent this sort of implicit promotion or implicit type conversion. For example, if Foo is really an array-like container and 42 is the initial size, you might want to let your users say, Foo x(42); or perhaps Foo x = Foo(42);, but not just Foo x = 42;. If that’s the case, you should use the explicit keyword:
**class** **Foo** { public:**explicit** Foo(int x); }; **class** **Bar** { public:**explicit** Bar(double x); }; void yourCode() { Foo a = 42; *//Compile-time error: can't convert 42 to an object of type Foo* Foo b(42); *//OK: calls Foo::Foo(int) passing 42 as an argument* Foo c = Foo(42); *//OK: calls Foo::Foo(int) passing 42 as an argument* Foo d = (Foo)42; *//OK: calls Foo::Foo(int) passing 42 as an argument* Bar x = 3.14; *//Compile-time error: can't convert 3.14 to an object of type Bar* Bar y(3.14); *//OK: calls Bar::Bar(double) passing 3.14 as an argument* Bar z = Bar(3.14); *//OK: calls Bar::Bar(double) passing 3.14 as an argument* Bar w = (Bar)3.14; *//OK: calls Bar::Bar(double) passing 3.14 as an argument* }
extern
A keyword used to indicate that the definition of an entity being declared is defined elsewhere (i.e., another file).
final
<small>Indicate that a derived class shall not override a virtual method.</small>
<small><span style="color: #008000; font-weight: bold;">class</span> <span style="color: #0000FF; font-weight: bold;">B</span> { <span style="color: #A0A000;">public:</span> <span style="color: #008000; font-weight: bold;">virtual</span> <span style="color: #B00040;">void</span> f(<span style="color: #B00040;">short</span>) {std<span style="color: #666666;">::</span>cout <span style="color: #666666;"><<</span> <span style="color: #BA2121;">"B::f"</span> <span style="color: #666666;"><<</span> std<span style="color: #666666;">::</span>endl;} }; <span style="color: #008000; font-weight: bold;">class</span> <span style="color: #0000FF; font-weight: bold;">D</span> <span style="color: #666666;">:</span> <span style="color: #008000; font-weight: bold;">public</span> B { <span style="color: #A0A000;">public:</span> <span style="color: #008000; font-weight: bold;">virtual</span> <span style="color: #B00040;">void</span> f(<span style="color: #B00040;">int</span>) override final {std<span style="color: #666666;">::</span>cout <span style="color: #666666;"><<</span> <span style="color: #BA2121;">"D::f"</span> <span style="color: #666666;"><<</span> std<span style="color: #666666;">::</span>endl;} }; </small>
What is the Free Store?
- The free store is one of the two dynamic memory areas, allocated/freed by new/delete.
- Object lifetime can be less than the time the storage is allocated; that is, free store objects can have memory allocated without being immediately initialized, and can be destroyed without the memory being immediately deallocated.
- During the period when the storage is allocated but outside the object’s lifetime, the storage may be accessed and manipulated through a void* but none of the proto-object’s nonstatic members or member functions may be accessed, have their addresses taken, or be otherwise manipulated.
Function Object/Functor
- Function objects can maintain state but require the syntactic overhead of a class definition.
- For a basic problem, the simpler lambda design is probably better than the function-object design. However, if the functionality might require significant expansion in the future, then it is better to use function object design so that code maintenance will be easier.
Function Pointer
**typedef** int(\*FunPtr)(int); int Square(int n) { **return** pow(n,2); } int Cube(int n) { **return** pow(n, 3); } void main(int argc, char \*argv[]) { FunPtr ptr; ptr = Square; cout \<\< ptr(2) \<\< endl; ptr = Cube; cout \<\< ptr(2) \<\< endl; }
Name of a function by itself, without parentheses, is a function pointer.
Explain how function templates work
What is Global/Static?
Global or static variables and objects have their storage allocated at program startup, but may not be initialized until after the program has begun executing. For instance, a static variable in a function is initialized only the first time program execution passes through its definition. The order of initialization of global variables across translation units is not defined, and special care is needed to manage dependencies between global objects (including class statics). As always, uninitialized proto- objects’ storage may be accessed and manipulated through a void* but no nonstatic members or member functions may be used or referenced outside the object’s actual lifetime.
Hash Map
What is a Hash Table?
- Hash table is a data structure used to implement an associative array, a structure that can map keys to values.
- A hash table uses a hash function to compute in index into an array of buckets or slots, from which the correct value can be found.
What is the Heap?
The heap is the other dynamic memory area, allocated/freed by malloc/free and their variants. Note that while the default global new and delete might be implemented in terms of malloc and free by a particular compiler, the heap is not the same as free store and memory allocated in one area cannot be safely deallocated in the other. Memory allocated from the heap can be used for objects of class type by placement-new construction and explicit destruction. If so used, the notes about free store object lifetime apply similarly here.
Increment and Decrement Operator Overloading
When the postfix increment and decrement appear in an expression, the corresponding user-defined function (operator++ or operator–) is called with an integer argument 0. Typically, it is implemented as T operator++(int), where the argument is ignored. The postfix increment and decrement operator is usually implemented in terms of the prefix version:
**class** **Point** { public: Point& **operator**++(); *// Prefix increment operator.* Point **operator**++(int); *// Postfix increment operator.**// Define default constructor.* Point() { x = 0; } private:int x; }; *// Define prefix increment operator.* Point& Point::**operator**++() { ++x;**return**\***this**; } *// Define postfix increment operator.* Point Point::**operator**++(int) { Point temp = \***this**; ++\***this**; or**operator**++();**return** temp; }
What are different iterator types?
- Input - reads forward (istream)
- Output - writes forward (tream/inserter)
- Forward - reads and writes foward
- Bidirectional - reads and writes foward and backward (list/set/multiset/map/multimap)
- Random access - reads and writes with radom access (vector/deque/string/array)
What is L”xxx”?
Wide string literal, represented as L”xxx”.