Effective C++ Quiz
Name 2 functions that copy data into its object instance.
1. copy constructor 2. copy assignment operator
Identify the types of constructors below: 1. Widget(); 2. Widget(const Widget& rhs); 3. Widget& operator=(const Widget& rhs);
1. default constructor 2. copy constructor 3. copy assignment operator
Which constructors get invoked? 1. Widget w1; 2. Widget w2(w1); 3. w1 = w2; 4. Widget w3 = w2;
1. default constructor 2. copy constructor 3. copy assignment operator 4. default constructor and copy assignment operator
Name the types of initialization in C++
1. int b = 5; // copy initialization 2. int c(6); // direct initialization 3. int d { 7 }; // list initialization
What's the difference between: 1. const std::vector<int>::iterator iter = vec.begin(); 2. std::vector<int>::const_iterator cIter = vec.begin();
1. iter acts as a T* const where its a constant pointer to type T. Address of where pointer points to can't change 2. cIter acts like const T* where its a pointer to type T that is constant value. Its value can't change but you can modify the memory address it points to.
Name some smart pointers
1. shared_ptr -> does reference counting under the hood and deallocates the resource when ref count is 0 2. unique_ptr -> only allowed to hold 1 reference to resource on the heap (assigning to a new unique_ptr will cause the old unique_ptr to point to null) 3. weak_ptr -> object managed by shared_ptr and does not affect object's ref count
What is aliasing?
Having more than one way to refer to an object a[i] = a[j]; // could potentially be assignment to itself if the address at a[i] is the same as the address at a[j]
True or False? Never return a pointer or reference to a local stack object, a reference to a heap-allocated object, or a pointer or reference to a local static object if there is a chance that more than one object will be needed.
True
True or false. Avoid using objects when object references or pointers will do.
True
True or false. Using the inline keyword on a function is a request for the compiler to replace every call site of that function with its function body.
True
True or false? Don't call virtual functions during construction or destruction, because such calls will never go to a more derived class than that of the currently executing constructor or destructor.
True
True or false? If you need type conversions on all parameters to a function (including the one pointed to by this pointer), the function must be a non member
True
Using handle classes and interfaces are good when you want to minimize impact when implementation details change
True
Virtual inheritance imposes costs in size speed and complexity of initialization and assignment. Pure virtual classes are practical (like interfaces in c#)
True
True or False, Two objects need to be declared of the same type given they're from the same hierarchy.
True, because base class reference or pointer can refer or point to an object of a derived class type. class Base { ... }; class Derived: public Base { ... }; void doSomething(const Base& rb, Derived* pd); // rb and *pd could point to the same object
True or false. const data members must be initialized and cannot be assigned.
True, need to use const data members copy constructors to initialize its first value. Trying to use the = (assignment operator) will not work as the default constructors for the const data members have already been called before the constructor block is executed.
Depend on class declarations (forward declare) instead of class definitions whenever you can.
True. This is because if the class definition is included in the header file and the include has to be recompiled. The recompilation will also include the header file you have the include in. tl;dr takes longer time to recompile your code.
How many operations does this do under the hood? std::string foo = "bar";
Two because it makes a call to std:string's default constructor followed by the assignment operator to set foo's value to "bar"
T/F data members are initialized in the order they are declared.
True
T/f both classes and templates support interfaces and polynorphisn
True
T/f to prevent hiding overloaded virtual base functions from derived classes, use using keyword e.g using Base::mf1;
True
True or False? If you use [] in a new expression, you must use [] in the corresponding delete expression.
True
True or False? Compilers may implicitly generate a class's default constructor, copy constructor, copy assignment operator, and destructor
True
What is a memory leak?
when application requests memory on the heap but never releases it (memory stays in the RAM)
Why Prefer consts, enums, and inlines to #defines?
#define ASPECT_RATIO 1.653 const double AspectRatio = 1.653 const variables are seen by compilers and entered into sym tables #define variables may introduce multiple copies of same value but substituted in by the pre-processor
Where can the keyword const be used in?
* can be used in global or namespace scope * can be used on a function * inside of classes, can be used for both static and non-static data members * for pointers, can specify whether the pointer is const, the data it points to is const, both, or neither
What are some costs or tech debt that will need to be handled if all data members in a class are made public?
1. Code will need to be rewritten 2. Code will need to be retested 3. Code will need to be redocumented 4. Code will need to be recompiled
What are some reasons to keep data members private in a class?
1. Gives clients syntactically uniform access to data 2. Affords fine-grained access control 3. Allows invariants to be enforced 4. Offers class authors implementation flexibility
What is Object Slicing Problem?
A derived class object can be assigned to a base class object but not the other way around. E.g. class Base { int x, y; }; class Derived : public Base { int z, w; }; Derived d; Base b = d; // Object Slicing, z and w of d are sliced off
What is a pure virtual function?
A function that is required to be implemented by a derived class if not abstract virtual void foo() = 0;
What is const?
A particular object should not be modified where the compiler enforces that constraint after an initial value to the variable is already assigned
Why use a virtual destructor and what is it?
A virtual destructor allows us to delete a derived class object from the heap. Not making the destructor of a base class not virtual may cause its derived class data members to not properly release its memory off the heap (undefined behavior)
What does member initialization look like in a C++ constructor?
ABEntry::AbEntry(const std::string& name, const std::string& address, const std::list<PhoneNumber>& phones) : theName(name), theAddress(address), thePhones(phones), numTimesConsulted(0) {}
What is a static object?
An object that exists from the time it's constructed until the end of the program. Object is destroyed automatically when program exists (Their destructors are automatically called when main() finishes executing)
What is the difference between assignment and initialization?
Assignment: gives a variable a value at some point after the variable is created Initialization: sets an initial value for an object who has no value set by the program yet
What kinds of guarantees are there for exception-safe functions?
Basic Guarantee, Strong Guarantee, and No throw exception guarantee
Encapsulation
Bundling data and functions together into a single unit.
What causes a segmentation fault?
Caused when program tries to read or write an illegal memory location
What is the non virtual interface idiom?
Clients call private virtual functions indirectly through public non virtual member functions
Why is pass-by-reference-to-const usually better than pass-by-value for user defined objects in C++?
Copies are created silently by the user defined object's copy constructor which is why C++ passes objects to and from functions by value! No new objects are being created by the constructor (can have user defined types defined in a class which will then call constructors for those classes)
What technique is good to handle exceptions safely?
Copy and swap - make a copy of object to modify. Modify copy and if successful swap copy with original object
What is template metaprogramming?
Creation of programs that execute inside c++ compilers and stop running when compilation complete
How to make sure copy constructor and copy assignment operators aren't declared for you when creating classes by default?
Declare them as private members of the class
(specific question): What is "copy and swap" technique and how useful is it for making sure operator= is exception and self-assignment safe?
Example of how its done: class Widget { ... void swap(Widget& rhs); // exchange *this's and rhs's data } Widget& Widget::operator=(const Widget& rhs) { Widget temp(rhs); // make a copy of rhs's data swap(temp); return *this; } // Shorter way Widget& Widget::operator=(Widget rhs) // is passed by value which makes a copy of the original data source and once it leaves function scope, its data gets popped off the stack { swap(rhs); // swapping this data with rhs data is ok here since rhs is just a copy of the original source being passed in by value return *this; }
True or false. Exception safe code must offer all 3 guarantees (basic, strong, and no throw guarantees) to be valid.
False
T/f non virtual functions are dynamically bound whereas virtual functions are statically bound.
False non virtual functions are statically bound so if you refer to a pointer to base class you run that base class function and if you refer to pointer to derived class, you run derived class function If D derives from B and both contain same virtual function signature, it will call the derived virtual function given that the pointer to the object is the derived type
True or False? Compilers will not generate a copy constructor or copy assignment operator for you.
False, the compilers may define the copy constructor and copy assignment operator.
True or false. In C++ when an int is uninitialized, it defaults to the value 0.
False, this only is applicable in C# whereas in C++ this is considered undefined behavior Its important to always initialize objects before being used
T/F derived classes are initialized before base classes.
False. Base Classes are initialized before derived classes.
T/f prefer runtime errors to compile time errors whenever possible
False. Should prefer compile time errors over runtime so that getting the error earlier is generally better
True/False. STL Container types such as vector, list, set, unorder_map have virtual destructors
False. These do not have virtual destructors
What is an invariant?
In math, an invariant is an object which remains unchanged after operations or transformations of a certain type are applied to the objects. An invariant is something (or a property) that doesn't change after applying transformations onto said object. In solving algorithms, identifying what the invariant (or constant based on logical reasoning) is an important skill to have because it will allow you to tackle problems from different problem spaces.
Non virtual functions both ______ and ______ must be inherited
Interface and implementation
Virtual function means "interface ________ be ________"
Interface must be inherited
What is reference-counting smart pointer? (RCSP)
Is a smart pointer that keeps track of how many objects point to a particular resource and automatically deletes the resource when nobody is pointing to it any longer. Drawbacks of using this is that reference-counting smart pointers can't break cycles of references
What is an iterator in C++?
Is any object that pointing to some element in a range of elements (such as array or container) has ability to iterate through the elements of that range using a set of operators Can be thought of as T* pointers (generic pointers of type T)
Why prefer non-member non-friend functions to member functions (e.g. convenience functions)?
It helps increase encapsulation, packaging flexibility, and functional extensibility
What is an auto_ptr in C++?
It is a type of smart pointer whose destructor automatically calls delete on what it points to (deprecated in c++ 11) Reason: https://stackoverflow.com/questions/3697686/why-is-auto-ptr-being-deprecated See unique_ptr as an alternative
What does private inheritance mean in c++?
It means "is implemented in terms of" relationship. A student is implemented in terms of a person. Private inheritance means inherit implementation only but not the interface
What does pass-by-value mean when used in a function?
It means to call the copy constructor
What does explicit keyword do for constructors?
It prevents the class instances from being used to perform implicit type conversions class B { public: explicit B(int x = 0, bool b = true); }
What is a default constructor?
One that can be called without any arguments
Non-virtual function?
Non virtual function specify inheritance of interface and inheritance of mandatory implementation
What is initialization
Process of giving an object its first value. Usually is performed by constructors.
What is a definition?
Provides compilers with the details a declaration omits. For an object, the ____ is where compilers set aside memory for an object. For a function or function template the ____ provides the code body.
Why is reassigning pointers comparatively cheaper than using a copy constructor?
Reassigning pointers is cheaper because you only need 4 bytes (memory address) to change where the new resource is located. Copy constructors can be expensive because they may contain multiple private data members that need to call their own copy constructors (imagine a class with several string data members declared that need to be initialized via default constructor)
What is an inline function? What are some trade offs using it?
Replace each function call of that function with its code body. 1 drawback is that it increases size of your object code Inlining happens during the compilation process
What does RAII stand for?
Resource Acquisition Is Initialization: Binds life cycle of a resource must be acquired before use to the lifetime of an object * encapsulate each resource into a class where: * constructor acquires the resource and establishes all class invariants or throws an exception if that cannot be done. * the destructor releases the resource and never throws exceptions. examples that follow RAII are std::string std::vector std::jthread
What is undefined behavior? Some examples?
Some constructs in C++ is not literally defined by the language so the results of some things declared can't be reliably predicted at runtime. * dereferencing a null pointer int *p = 0; // null ptr std::cout << *p; // dereferencing null pointer yields in undefined behavior * referring to an invalid array index yeields undefined behavior char name[] = "Darla"; char c = name[10];
What is a client?
Someone or something that uses the code you write
What is STL? and what kinds of containers does it have?
Standard Template Library part of C++'s standard library that have containers such as vector, list, set, and map * iterators vector<int>::iterator * algorithms (for_each, find, sort)
What is a declaration?
Tells compilers about the name and type of something, but omits certain details extern int x;
What is "implemented in terms of" mean in OOP?
The class contains an existing data structure you want to represent when creating a new data structure. E.g creating a set class using a list as a private member of the class.
What is the purpose of const on member functions?
The purpose of ______ on ______ functions is to identify which member functions may be invoked on const objects
Why are explicit constructors preferred to non-explicit ones?
They prevent compilers from performing unexpected or unintended type conversions
T/f multiple inheritance more complex than single inheritance
Tru
In c++ inheritance means "is a" relationship
True
Inheritance in c++ can either be single or public (t/f)?
True
It's good practice to provide separate header files for declarations and definitions .h and .cpp files
True
Public inheritance is a "is a" inheritance. Everything that applies to base classes must apply to derived object.
True
What is a good rule of thumb of when to use pass by reference to const vs pass by value?
Use pass by value for built-in types such as ints and chars, Use pass-by-reference-to-const for user defined objects generally because their copy constructors could contain expensive computations (copy every value can be expensive)
How can object slicing be prevented?
Use pointers or references instead of copying by value because pointers and references take the same amount of memory. void somfunc (Base &obj) { obj.display(); // or can use Base *obj // obj->display(); won't slice off the extra variables and/or functions that was part of the derived class }
What is compile time polymorphism?
Used in generic and template programming. It is instantiating function templates with different template parameters which lead to different functions being called.
What is the copy assignment operator used for?
Used to copy value from one object to another of the same type
What are resource-managing or smart pointers useful for?
Useful for guards against memory leaks due to the destructor automatically deallocating resource encapsulated Useful when you want a class to manage some of the memory management for you (not deal with raw pointers)
Virtual function?
Virtual functions specify inheritance of interface and inheritance of default implementation
What is the diamond problem?
When data members of the base class get replicated per instance when d class inherits from c and b classes. C and b classes inherit from class a (root base class) To prevent replicated data members c and b classes must inherit from class a using virtual keyword Class c : virtual public a Class b : virtual public a
How to read this pointer? Widget *pw;
Widget *pw; // pw = ptr to Widget
Is multiple inheritance supported on c++?
Yes
Which one is an operator[] for const objects and which operator[] is for non-const objects? a. char& operator[](std::size_t position) { return text[position]; } b. cont char& operator[](std::size_t position) const { return text[position];}
a. operator for non-const objects b. operator for const objects
What do pure virtual functions result in? What are they also known as in C++?
abstract classes class AWOV { public: virtual ~AWOV() = 0; } AWOV::~AWOV() {}
What is "enum hack" useful for?
class GamePlayer { private: enum { NumTurns = 5 }; // creates a symbolic name for 5 int scores[NumTurns]; // fine } Useful if you don't want people to get a pointer or reference to one of your integral constants
What is ctor and dtor short for?
constructor and destructor
What do the following statements mean in english? void f1(const Widget *pw); void f2(Widget const *pw);
f1 is a function that takes a pointer to a constant widget f2 is a function that takes a pointer to a constant widget Both are equivalent in meaning
What's wrong with the following code? and how to fix? Widget& Widget::operator=(const Widget& rhs) { delete pd; pb = new Bitmap(*rhs.pb); return *this; }
if doing a self assignment Widget w1; w1 = w1; will fail because it holds a pointer to a deleted object. To fix, do a identity check before deleting the resource off the heap if (this == &rhs) return *this; // identity test: if a self-assignment
What is bitwise constness?
member function is const if and only if it doesn't modify any of the object's data members (exclude static members), if it doesn't modify any of the bits inside the object
What does mutable keyword do?
mutable keyword allows non-static data members in a class to be modifiable (release constraints from bitwise constness)
What is a function's signature?
std::size_t numDigits(int number) Function that specifies its return type and parameters it takes in to produce the returned result (e.g. the output)
What is a copy constructor?
used to initialize an object with a different object of the same type
Fill in the blanks Polymorphic base classes should declare ____ destructors. If a class has any ____ functions, it should have a _____ destructor
virtual