Programming exam Flashcards
Declaration/ header (.h)
In the header file, a developer provides the declaration of a class’ interface. In essence, this gives the “shape” of the class
Definition/Implementation (.cpp)
In the definition file, a developer provides the code that is run each time a function member is called.
Use/ Driver (.cpp)
In a driver file, an external program references the header file using a #include statement and uses the class members (via objects or instances of that class) to solve a problem.
Class Declaration
A class declaration takes this general form
class <class>{
private:
//a series of private data and function member declarations
public:
//a series of public data and function member declaration</class>
Class Definition
The definition of a class provides definitions for functions that are declared in the class declaration. This linking is performed using the scope resolution operator “::” between the class name and the member name. An example definition would look like this:
<return> <class>::<function> (<parameter>) {
//code goes here
}
</parameter></function></class></return>
Using a Class
In a driver program, one would first create instances of a class by declaring a variable of the appropriate type:
Employee e;
After the variable is declared, the programmer now has access to all of the public data and function members using the class member access operator, also known as the “dot” operator:
e.Inactivate()
Compiling a Class and Driver
While one could use a single command approach to compilation, it is better to use a multi-step approach that separates the header file from compiled source code. An example compilation of a class and driver with the three files outlined above would be:
Step 1: g++ -c <class>.cpp
Step 2: g++ -c <driver>.cpp
Step 3: g++ <class>.o <driver>.o -o <desired>.exe
In English:</desired></driver></class></driver></class>
Step 1: compile the class source code into consumable object code
Step 2: compile the driver class into object code
Step 3: link the class object code with the driver object code to create an executable file
Private class members
can only be accessed within the definition of a class. That is, any attempt to reference a private data or function member from a function or code location that is not associated with the same class using the scope resolution operator (::) is a syntax error.
Public class members
can be accessed from anywhere an object of the appropriate type is available. The most common example would be a driver program using public function members from an object of a class declared as a local variable within that driver program.
Constructors
Constructors are special function members that are used to create objects or instances of a class. These functions contain behavior that is run when a driver program creates a variable with the type of your class.
Initialization: Initialize the object’s attributes when it is created.
Same Name as Class: It has the exact same name as the class.
No Return Type: Constructors do not have a return type, not even void.
Automatically Called: It gets called automatically when an object is created.
Accessors
are public function members used to access the private value
Mutators
are public function members used to change the private value.
Getters
are accessors that only provide access to a private data member.
Setters
are mutators that set a private data member to a value specified as a passed in parameter
A(n) ___________ function has access to both public and private data members of a class but is NOT a member function:
friend
Classes encapsulate two types of members: function members that define business logic and ______ members that define the state of a class.
data
_______ is a keyword used to ensure that conversion constructors are NOT used implicitly.
explicit
The _______ operator is used to link a member function to a class.
::
The _____ design methodology is used when creating a C++ program or class.
DDU
When creating an operator override, the keyword _______ is used to name the implementation method:
operator
The name of a destructor must begin with the special character:
~
A(n) ________ is used to set constant data members of a class:
Initialization list
++ is a(n) _______ operator.
Unary
The keyword “friend” is used in a functions’s:
Declaration
Conversion constructors can accept multiple paramters (T/F)
False (can only have one parameter, its the type its converting from)
Destructors accept only one parameter (T/F)
False
A class can have only one implementation of an override for a given operator (T/F)
True
A driver program cannot access private data or function members. (T/F)
True
Constant member functions can call other non-constant functions. (T/F)
False
A class can have an arbitrary number of constructors. (T/F)
True
The -c flag is used to create object code from a source cpp file with g++. (T/F)
True
Classes are instances of objects. (T/F)
False
A driver program can create an arbitrary number of objects from a class. (T/F)
True
A setter should always be marked const. (T/F)
False
A ________ member can be accessed outside of the class implementation but a ______ member cannot.
public, private
Getters are a special type of ______ that provide access to _____ state.
accessor, private
A _________ is a special function member that specifies defaulting logic for a class’ data members.
Constructor
Which of the following is TRUE about constructors?
They are a function with the same name as the class
The header file is responsible for declaring the ________ for a class
interface
What are the two steps in the compilation process for C++?
Compile step and linking step
What is the correct g++ flag to perform only the compile step of compilation?
-c
Which of the following file extensions is used to declare a programming interface in C++?
.h
A programming ___________ provides a public menu of behavior and state that can be used by a consuming piece of code
interface
What is the C++ operator that is used to “connect” a function definition to a class declaration( i.e, the scope resolution operator)?
::
A _________ class is another name for a main class that consumes a piece of code.
driver
To create a friend function, the “friend” keyword is used in the definition of the function. (T/F)
False
True or False: The scope resolution operator is NOT needed when defining a friend function.
True
True or False: All conversion constructors are parameterized constructors but not all parameterized constructors are conversion constructors.
True
True or False: Only one class can be declared within a header file.
False
True or False: Friend functions must always be public.
False
True or False: Const member functions can only call other const functions.
True
How many times would the word “const” appear in the declaration of a constant function that returns a constant value and takes in two constant parameters by value?
4
True or False: In C++, you can create a non-constant object that contains constant data members and constant function members.
True
What is the naming convention for a destructor in C++?
A destructor should always be named with a tilde (~) followed by the class name. For example: ~ClassName().
Where should destructors be declared and can they have parameters?
Destructors should always be declared in the public section of the class and they do not take any parameters.
How many destructors can a class have and do they need to be explicitly called?
A class can only have a single destructor. Destructors are called implicitly when an object instance falls out of scope, so they do not need to be explicitly called.
When is it necessary to define a custom destructor for a class?
It’s necessary to define a custom destructor if the class contains an unmanaged resource like a database connection, a file handle, or contains a pointer to memory allocated within the class definition. Otherwise, the default destructor is often sufficient
What is the primary purpose of a destructor?
The primary purpose of a destructor is to release resources and perform cleanup when an object is destroyed, which occurs when it goes out of scope, such as when a function returns or a conditional code block containing the declaration of the object ends.
True/False: All objects are given a default destructor in C++
True. All objects are provided a default destructor in C++, which in many cases is all that is needed, especially when the class doesn’t manage any external resources or allocate dynamic memory.
What are some scenarios in which a destructor is called?
A destructor is called implicitly when an object falls out of scope, such as when a function returns, a conditional code block containing the declaration of the object ends, or when the program execution leaves the scope in which the object is defined.
What are the three main components of operators in C++?
Operators in C++ have three main components: a return type, a name, and a list of parameters.
Can you change the precedence, associativity, or the number of parameters of an operator in C++?
No, you cannot change the precedence, associativity, or the number of parameters of an operator in C++ during operator overloading
What is “arity” in the context of operators, and what are its types?
“Arity” refers to the number of parameters that an operator accepts. Unary operators accept one parameter, binary operators accept two, and (although rare and not directly supported in C++) tertiary operators would theoretically accept three.
How must operators be named when being overloaded in C++?
When overloading operators in C++, they must be named using the keyword “operator” followed by the operator symbol being overloaded. For example, overloading the plus operator would be named “operator+”.
Can you create new operators or change the behavior of operators on primitive or built-in types in C++?
No, you cannot create new operators or change the behavior of operators on primitive or built-in types in C++.
Can operator overloads be implemented as both member and friend functions, and is there a general rule on which to use?
Yes, operator overloads can be implemented as either member or friend functions. There’s no hard and fast rule, but member function operator overloads are typically used unless the left operand needs to be converted, which requires a friend function.
What is encapsulation in the context of classes in C++?
Encapsulation is a core coding practice where different data types (like int, string, etc.) are bundled together into a user-defined type (e.g., a class named “Employee”). This allows for easier storage and retrieval of data related to specific entities and also enables associating behavior (functions) with data (data members).
What are the data members in a class and what do they represent?
Data members in a class, often referred to simply as “members” in C++, are variables declared within a class. They represent the state of an object, holding values that define properties or attributes of objects created from that class.
What are function members in a class and how do they relate to encapsulation?
Function members, or member functions, in a class encapsulate behavior that is directly related to objects of the class. They perform operations on the object’s data members or interact in some way with the object’s state, ensuring that behavior relevant to the data is kept together with the data itsel
If classes are considered blueprints, what are objects in C++?
Objects in C++ are instances of classes. If a class provides the blueprint (defining properties and behaviors), an object is an individual instantiation of that class, with its own specific state defined by the values of the data members. For example, if Employee is a class, empl1 could be an object of type Employee.
What is the distinction between private and public class members in C++?
Private class members can only be accessed within the class’s definition, whereas public class members can be accessed from any location where an object of the class type is available, including from functions in a driver program.
In general, how should data members and function members be designated in terms of access modifiers, and why?
Data members should mostly be private to prevent unintended states by external code and to maintain encapsulation.
Function members should be public if they offer functionality meant to be accessed externally.
Function members should be private if they are meant for internal use within the class, and not to be used by external or driver code.
Can one instance of a class access private members of another instance of the same class in C++?
Yes, one instance of a class can access private members of another instance of the same class because they share the same definition. However, this can be considered unsafe practice in many cases, especially when internal data validation standards need to be met through public accessors.
Why might it be considered unsafe or unwise to directly access private members of another instance of the same class?
Direct access to private members might bypass internal data validation which is often implemented through public accessors, potentially allowing the object to enter an invalid state. Using public accessors, even within the class definition, ensures that all interactions with the data adhere to the validation and manipulation rules defined by the class.
What is the role of a constructor in C++?
Constructors are special function members in C++ used to create objects or instances of a class, initializing their state, and executing any behavior that needs to occur when an object is created.
Are constructors typically public or private, and why?
Constructors are typically declared public because they need to be accessible to driver programs or other code outside the class, enabling them to create objects of the class type.
Can you have multiple constructors and how are they typically used?
Yes, a class can have multiple constructors, including the default constructor and parameterized constructors that accept arguments to initialize the object in specific ways. Parameterized constructors allow objects to be initialized with specific data at the time of creation.
What is a conversion constructor and how is it used in C++?
A conversion constructor is a constructor that takes a single parameter and allows implicit conversion from the type of its parameter to the class type.Example:
Employee(int code);
allows
Employee e = 10101; // implicit call to the conversion constructor
It converts the int value 10101 into an Employee object, using that value to initialize the object.
What is the explicit keyword in the context of constructors and why might it be used?
The explicit keyword prevents implicit conversions and requires that the constructor be called explicitly. If explicit is used in the declaration like:
explicit Employee(int code);
then implicit calls like Employee e = 10101; would result in a syntax error at compile time, and only explicit calls like Employee e(10101); would be allowed.
How are objects instantiated using constructors?
Objects can be instantiated by calling the constructor explicitly, like:
Employee e1, e2, e3;
// Default constructor
Employee e(10101);
// Parameterized constructor
or, if no explicit keyword is used with a single-parameter constructor, via implicit conversion, like Employee e = 10101;.
What is the primary purpose of accessors and mutators in a class?
Accessors are public function members used to access private data members, while mutators are used to modify them. They are utilized to implement encapsulation and data protection in a class, ensuring that data is accessed and modified in a controlled and safe manner.
Define getters and setters, and how do they specialize accessors and mutators?
Getters are a specialized type of accessor that solely provide access to a private data member.
Setters are a type of mutator that specifically set a private data member to a provided value.
Thus, all getters are accessors and all setters are mutators, but not vice versa due to the specialized use.
What is the typical naming convention for getters and setters?
The generally accepted naming convention for getters and setters is Get<PrivateMemberName> and Set<PrivateMemberName>, respectively. However, these names are related to their behavior, not strictly the function name, and alternative naming can be used.</PrivateMemberName></PrivateMemberName>
Why use getters and setters instead of directly accessing class members?
Getters and setters are utilized to enforce validation on private data members. While a public member can be set to any value, setters enable the implementation of logic that validates or modifies input before altering a private member. Similarly, getters can provide a validated or adjusted value upon read, ensuring controlled access to the internal state of an object and maintaining encapsulation.
What is a side effect in the context of object-oriented programming, and why is it significant in the context of getters and setters?
A side effect occurs when a function member modifies the state of an object in a manner not anticipated by the caller. It is generally considered undesirable in good class design. Getters and setters should ideally avoid side effects, focusing on singular responsibilities: getters should only retrieve values, and setters should only set values, both potentially with validation or transformation logic.
How can setters and getters ensure that the data members of an object maintain valid states?
Setters can incorporate validation logic to check and possibly modify input values before they are assigned to private data members, ensuring the object does not enter an invalid state. Getters can validate or adjust the stored data before providing it, ensuring that the value retrieved is valid or meets certain criteria, even if the internal state doesn’t.
Are mutators and setters the same?
No. While setters are a type of mutator, they are distinct in that setters specifically assign a provided value to a private data member. In contrast, mutators might modify private data members in varied ways, not limited to assigning a specific value. All setters are mutators, but not all mutators are setters.
How can getters be implemented to “clean” data upon a read?
Getters can implement logic that validates, transforms, or adjusts the private data before it is returned. This ensures that even if the internal state of the object is invalid or non-optimal, the value provided by the getter adheres to defined valid or safe parameters.
What is the distinction between private and public members in a class declaration?
Private members are only accessible within the class definition, while public members are accessible from outside the class definition, such as in a driver program.
How do you correctly call a member function of a class using an object of that class?
You need to instantiate an object of the class and then use the object to call the member function. For example:
Fraction(1,2).Add(Fraction(1,2));
Here, Add() is called on a Fraction object and another Fraction object is passed as a parameter.
What is a friend function in C++ class definition and how does it access class members?
A friend function is not a member of the class but is allowed to access its private and protected members. It is declared within the class using the “friend” keyword but is not considered a class member, so it doesn’t adhere to the public/private access controls.
Describe the metaphor of private possessions, public possessions, and friends in relation to class members and friend functions.
Private possessions (private members) are only available to you (the class). Public possessions (public members) are accessible to anyone you invite (any function or class). Friends (friend functions) can access your private possessions because of trust and closeness (they can access private and protected members of the class).
Why doesn’t the friend function use the scope resolution operator in its definition?
Friend functions do not use the scope resolution operator because they are not members of the class. They are defined without being scoped to the class, even though they are declared inside the class with the “friend” keyword
In the context of C++ coding, provide an example of defining a member function and a friend function to illustrate the difference in syntax.
Member function:
Fraction Fraction::Add(Fraction f) {}
Friend function:
Fraction Add(Fraction f1, Fraction f2) {}
The member function uses the scope resolution operator :: because it is a part of the class, whereas the friend function does not.
How is dot syntax utilized in member functions versus friend functions when accessing data members?
In a member function, the “current” instance accesses members directly or using this->, while parameters use dot syntax. In friend functions, dot syntax is used to access members of all objects passed as parameters since there is no “current” instance.
How do you declare a friend function within a class and what is its access level to the class members?
A friend function is declared within a class using the “friend” keyword and is placed outside of the public/private blocks since it is not truly a member and thus is not bound by the private/public access specifiers. It can access both private and protected members of the class.
How are parameters accessed within a member function versus a friend function when dealing with class instances?
In a member function, the “current” instance doesn’t require a specific object or the . operator to access its members. For the parameter objects, you would use dot syntax (e.g., f.numerator). In a friend function, since it is not bound to an instance of the class, all parameter objects would utilize dot syntax to access their members (e.g., f1.numerator, f2.numerator).