Exam 1 Study Guide
Picture ID is REQUIRED for all exams
Use the list of questions below as a guide when studying for Exam 1.
It is by no means a comprehensive list of questions.
You are responsible for all material presented in lecture.
You are also responsible for all associated reading assignments and material covered in lab.
Be sure to check out any student exercises found in the lecture notes.
Answering the "self-test" questions in each chapter of the text is also a good way to review.
For all TRUE/FALSE questions below which are FALSE, explain why.
General C++ Coding
- Write C++ code to output the sentence
"I am the Greatest" to the standard output device,
one word per line.
- Why is it necessary for the last line of main to be "return 0;"?
- What is the name of the standard input stream in C++?
- What is the name of the standard output stream in C++?
- What is argc? What is argv? What is their purpose?
- TRUE/FALSE
- Variables can be declared almost anywhere in the code.
- In a for loop a variable can be declared at the same time it's initialized
as in for (int i = 0; i < 42; i++).
- C++ supports the bool data type, but C does not.
- To use cout/cin, you must include the header file named iostream.
- Strings and vectors are built-in data types.
- argv[0] is always the name of your executable program.
Streams
- Define "stream". What are some advantages of using streams?
- Define cout, cerr and cin
- Write the code to create a stream named inFile, attach it to
a file named "input.txt", and then open the stream.
- Given a file that contains an unspecified number of integers separated
by white space,
write the code that reads all the integers from the file, adds them to a running sum,
prints the sum and closes the file.
- Describe two ways to check for EOF when reading a file.
- What is the output from the following code segment (assuming it's embedded in a complete
and correct program).
The file "input.dat" contains this single line of data:
1 23 4 567 8 90
ifstream in( "input.dat" );
int count = 0;
int item;
while ( in >> item )
{
++count;
cout << item << endl;
}
cout << count << endl;
- What is an I/O manipulator?
- Explain the effect of each manipulator -- fixed, showpoint, left, right, setprecision,
and setw
- What is the output from these statements?
double x = 42;
cout << fixed << showpoint << setprecision( 4 ) << x << endl;
- What output will be produced when the following lines of code are executed?
cout << "*" << setw( 5 ) << 123;
cout << left;
cout << "*" << setw( 5 ) << 123;
cout << right;
cout << "*" << setw( 5 ) << 123;
cout << endl;
Functions and member functions
- Why is function overloading possible in C++, but not in C?
- What is a function's "signature"?
- Explain the differences between the function prototypes below.
When would each prototype be appropriate?
char GetFirstCharacter ( string s );
char GetFirstCharacter ( string& s );
char GetFirstCharacter ( const string& s );
void GetFirstCharacter ( const string& s, char& c);
- You have been asked to write a set of four functions that find the smallest
element in a vector of ints, a vector of doubles, a vector of chars
and a vector of strings. You decide to use function overloading.
Write the prototypes for these four overloaded functions.
- In many cases, the use of default parameter values is an alternative
to function overloading. Give an example in which either method can be used.
Discuss why you might choose one method over the other.
- Why does this attempt at defining default parameter values result in
a compiler error/warning?
Vacation( int startMonth = 1 , int startDay, int duration = 0);
- Explain how the compiler decides which function to call when given
several functions with the same name.
- What is the cause of this typical compiler error?
BadSqrtPow.cpp: In function `int main()':
BadSqrtPow.cpp:10: call of overloaded `xxxx( int )' is ambiguous
- List the four basic ways that parameters can be passed to a function.
- Explain how "call by reference" in C++ is similar and different
than passing parameters with pointers in C.
- Explain when each method of parameter passing is appropriate for built-in
types like int and double.
- Explain when each method of parameter passing is appropriate for user
defined objects.
- Can a const object invoke a non-const member function? If so why?
If not, why not?
- Can a non-const object invoke a non-const member function? If so why?
If not, why not?
- Can a const object be passed as an argument by reference to a function?
If so why? If not, why not?
- Can a non-const object be passed as an argument by reference to a function?
If so why? If not, why not?
- Define PreConditon, PostCondition as used in function header
comments required by our coding standards.
- Explain three ways in which functions might handle unsatisfied PreConditions.
- What do we mean when we say that parameters and variables declared inside
a function are "local" variables.
- Do Self-Test exercise 25 on page 126 of the text to test your understanding
of variable scope.
- What is the scope of a variable declared in a 'for' loop control statement?
(i.e. for (int i = 0; i < size; i++)
- What is the output from the following code? Is it correct?
If not, how can it be fixed to print out the correct output?
// arrange n1 and n2 in sorted order
void Arrange(int n1, int n2);
int main ( )
{
int low = 44;
int high = 33;
Arrange (low, high);
cout << "Lowest = " << low << endl;
cout << "Highest = " << high << endl;
return 0;
}
void Arrange (int n1, int n2)
{
if (n1 > n2)
{
int temp;
temp = n1;
n1 = n2;
n2 = temp;
}
}
Strings and Vectors
- Given the declaration
string aString = "the quick brown fox jumped over the lazy dog";
write syntactically correct C++ code to
- Output the number of characters in aString to the standard output stream.
- Output the string backwards to the standard output stream.
- Instantiate a string object named anotherString as a copy
of aString.
- Explain the difference between using the input operator >> and using
the function getline( ) for reading strings input by the user or read from a file.
- Describe the potential problem when using both getline( ) and
the input operator >> to read strings and integers. How is this problem addressed?
- Write the function
bool FindSubString(const string& string1, const string& string2);
that returns true if string2 is a substring of string1; false otherwise.
Write this function without the use of any string "find" methods.
- Give at least three ways in which strings are superior to C-style
char arrays used as strings.
- Write the variable declaration for a vector of strings named text
- Write the variable declaration for a vector of 4 string named sentence
in which each string is initialized to "I love C++".
- Given that integers is a vector, what compiler error/warning,
will result from the statement int nrElements = integers.size( );
Rewrite the statement to eliminate the error/warning.
- Explain the difference between these two declarations
vector< int > v1( 10 );
vector< int > v2[ 10 ];
- Explain the difference between a vector's size and its capacity.
- Explain the difference between using brackets and the function at()
to access individual elements of a vector. When is each appropriate?
- In what ways are vectors like arrays?
- In what ways are vectors different from arrays?
- List 3 "bad things" about an array and how a vector is better at handling them.
- Given the declaration vector< int > vInt;
write C++ code that will store 2, 4, 6, 8, 10 in the vector in that order and
then print the contents of the vector.
Classes and Objects
- What is a class?
- The concept of a constructor may be confusing
because it is a member function of a class which is rarely explicitly called.
Explain when a constructor is called.
- Define "default constructor".
- Explain the difference between a class and an object
Use a "real life" entity as an example.
- Explain the OO design technique of "aggregation".
Explain how aggregation promotes code reuse.
- When using aggregation, some accessors will have a
return type of "reference to const". When is this return
type appropriate for an accessor? Why is this return type
used in this case?
- Discuss the pros and cons of having a mutator return a boolean
value indicating whether or not it was successful.
The following questions refer to the following class definition
class Car
{
public:
Car( int cylinders = 4, int passengers = 5,
const string& color = "Red");
void Start( );
void Stop( ) const;
void TurnLeft( );
void TurnRight ( );
const string& GetColor ( ) const;
int GetCylinders( ) const;
int GetNrPassengers( ) const;
void SetColor (const string& color);
void SetCylinders (int cylinders = 4);
void SetNrPassengers (int passengers);
private:
int m_cylinders;
int m_passengers;
string m_color;
bool m_isMoving;
};
- Write the code to implement Car's constructor.
- In how many ways may Car's constructor be invoked? List them.
- Write the code to implement Car's SetNrPassengers()
method.
- What is the significance of const in the
prototype for GetCylinders()
- What is the significance of const string&
as the return type in the prototype of GetColor().
- Write the declarations and code to instantiate a Car object for
a Black, 6-cylinder car that can hold two people. Write the code to start the Car.
- What is the significance of int cylinders = 4
as the parameter for SetCylinders()
- Under what circumstances can a user of Car directly access m_color?
- Identify the use of "aggregation" in the definition of Car (if any).
- Why does the following implementation of Stop result in a compiler
error?
void Car::Stop( ) const
{
m_isMoving = false;
}
- Define: member access specifier, object, instance, instantiation,
class scope, user, implementer, mutator, accessor, function signature
- Explain how the C++ features of private data members,
public methods, and public data members help or hinder the
OO objectives of encapsulation and data hiding.
- What is the "scope resolution operator" and what is its purpose?
- Define "zombie" object and one method for dealing with them.
- Which member function(s) has/have the responsibility for determine when
an object becomes invalid? Explain why.
- What is the purpose of a private member function?
- Given the following class definitions
class Point class Circle
{ {
public: public:
Point( int x = 0, int y = 0); Circle (const Point& p, int radius);
int GetX ( ) const; const Point& GetCenter( ) const;
int GetY ( ) const; int GetRadius( ) const;
void Move (int deltaX, int deltaY); void Alter (const Point& newCenter);
void Alter (int newRadius);
private: private:
int m_xcoordinate; Point m_center;
int m_ycoordinate; int m_radius;
}; };
and the declarations
Point point(3, 6);
Circle circle1 (point, 5);
Circle circle2 (Point (1, 2), 3);
- Write the implementation of Circle's Alter( const Point& newCenter) method.
- Explain the relationship of Circle's Alter( ) methods in the context of aggregation.
- Write the implementation of Circle's GetCenter() method.
- Write the implementation of Circle's constructor with and without using a member initialization list.
- Write one line of code to output the x- and y- coordinates of
circle2's center.
- Write one line of code to make circle2
and circle1 concentric (i.e. have the same center).
-
- Find the errors in the following statements (if any)
- Point p = (1, 3);
- Point p2;
- Circle c;
- cout << circle1.GetX() << endl;
- circle1 = circle2;
- Assume that you are asked to write the function PrintPoint( const Point& point );
that prints a Point object in the format ( x, y ). Would you choose to make
PrintPoint() a friend of the Point class above or not? Justify your answer.
- If you were required to write PrintPoint() as a friend of the Point class, where
would the prototype for PrintPoint() be found? Write the prototype for PrintPoint()
if it were a friend of Point.
- What does it mean for a function to be a friend of a class?
- Some people argue that the use of friendship violates the
principles of encapsulation. What do you think? Justify your position.
- Explain what we mean when we say that static data members are "restricted global variables".
- True/False - Static data members of a class are shared among all objects of that class.
- True/False - Static functions of a class can only access static data members of that class.
- True/False - Every member function of a class can access the static data members of that class.
- True/False - Static data members are declared and initialized outside the class.
- True/False - Static data members may not be const.
Operator Overloading
Use the class definition of Fraction for the questions below
class Fraction
{
public:
Fraction (int numerator = 1, int denominator = 1);
int GetNumerator( ) const;
int GetDenominator( ) const;
// other public methods???
private:
int m_numerator;
int m_denominator;
};
- Write the prototype for operator<< for Fraction.
- Write the code for operator<< assuming operator<<
IS NOT a friend of Fraction.
- Write the code for operator<< assuming operator<<
IS a friend of Fraction.
- Explain why operator<< CANNOT be a member function of Fraction.
- Write the prototype for operator+ that adds two Fractions and returns
a Fraction as a result, if operator+ is a member function of Fraction.
- Write the prototype for operator+ that adds two Fractions and returns
a Fraction as a result, if operator+ is NOT a member function of Fraction.
- Which version of operator+ is most useful? Explain your answer.
- Write the prototype for the unary negation operator (operator-) for Fraction.
- Write the prototype for the pre-increment operator of class Fraction
if is declared as a friend function.
- What functions must Fraction support if overloaded operators are written
as non-member, non-friend functions?