Part I: Multiple-Choice / True-False Questions

Download as pdf or txt
Download as pdf or txt
You are on page 1of 8

C++ Programming

Page 1 of 8

Dr R.K. Singla

Part I: Multiple-Choice / True-False Questions


1. Which command line option is used with g++ for generating profiling information?
a.
b.
c.
d.
e.

-c
-g
-pg
-Wall
none of the above

2. A function void hcf(Object& obj) is given. Which of the following statements about
what happens when hcf is called is true?
a.
b.
c.
d.
e.

the constructor for obj is called before entering the function


the copy-constructor for obj called before entering the function
the constructor for obj is called after entering function
the copy-constructor for obj called after entering function
none of the above

3. When a virtual function definition is changed in a derived class, it is said to


______________ the definition in the base class.
a.
b.
c.
d.
e.

overload
override
redefine
overshadow
shadow

4. A class D is derived from a class B; b is an object of class B, d is an object of class D, and


pb is a pointer to class B object. Which of the following assignment statements is not valid?
a.
b.
c.
d.
e.

d = d;
b = d;
d = b;
*pb = d;
all are valid

5. Which of the following statements is not true?


a.
b.
c.
d.
e.

a pointer to an int and a pointer to a double are of the same size


a pointer must point to a data item on the heap (free store)
a pointer can be reassigned to point to another data item
a pointer can point to an array
a pointer can point to a function

6. Which of the following STL template class is a container adaptor class?


a.
b.
c.
d.
e.

stack
list
deque
vector
none of the above

7. What kinds of iterators can be used with vectors?


a.
b.
c.
d.
e.

forward iterator
bi-directional iterator
random-access iterator
all of the above
none of the above

C++ Programming

Page 2 of 8

Dr R.K. Singla

The following class declaration is given:


class MyStr
{
public:
MyStr();
MyStr(int capacity);
MyStr(const char *str);
MyStr(const MyStr& mystr);
MyStr& MyStr::operator=(const MyStr& mystr);
bool MyStr::operator==(const MyStr& mystr);
bool MyStr::operator>(const MyStr& mystr);
bool MyStr::operator<(const MyStr& mystr);
MyStr& MyStr::operator+=(const MyStr& mystr);
const MyStr MyStr::operator+(const MyStr& mystr);
void
void
int
const

append(const char *str);


clear();
length() const;
char* c_str() const;

~MyStr();
friend ostream& operator << (ostream& ostr, const MyStr& mystr)
{ ostr << mystr.data; return ostr; }
private:
char *data;
};

Questions 8-14 refer to the use of the MyStr class given above. The variables s, s1, and s2 are
all objects of class MyStr.
Answer whether the following relational comparisons are valid or not (T is valid, F is invalid):
8.

s == "Test"

9.

"Test" == s

10. s1 > s2

11. s1 >= s2

12. s == 5

13. cout << "Test " << s << endl;

14. cin >> s;

Are the following statements valid or not (T is valid, F is invalid):

C++ Programming

Page 3 of 8

Dr R.K. Singla

Part II: Program Code


1. (3 marks) Name three things that are wrong with the following program (no need to correct
the errors):
#include <iostream>
#include <cstring>
using namespace std;
class Pet
{
public:
Pet(const char *name) { m_name = new char[strlen(name)+1];
strcpy(m_name, name); }
~Pet()
{ delete [] m_name; }
virtual void info() const = 0;
private:
char *m_name;
};
class Dog : public Pet
{
public:
Dog(const char *name, const char* breed)
: Pet(name)
{ m_breed = new char[strlen(breed)+1];
strcpy(m_breed, breed); }
~Dog()
{ delete [] m_breed; }
virtual void info() const
{ cout << m_name << " is a " << m_breed << endl;}
private:
char *m_breed;
};
void DeletePet(Pet *p) {
delete p;
}
int main()
{
Dog *d = new Dog("Fido", "Husky");
d->info();
DeletePet(d);

Pet *p = new Pet("Fluffy");


DeletePet(p);

Answer: __________________________________________________________________
___1. Destructors need to be declared virtual to avoid memory leak. _______________
___2. Cannot declare an object of class Pet because Pet is an abstract class.________
___3. The pet member variable m_breed cannot be accessed in the derived class.____
_________________________________________________________________________
2. Give a declaration of an array (named arr) of three function pointers, each
pointing to a function that takes one double argument and returns a character pointer.
Answer: ____ char* (*arr[3])(double); __________________________________________

C++ Programming

Page 4 of 8

Dr R.K. Singla

3. (3 marks) What does the following program output?


#include <iostream>
typedef int (*PTRFUNC)(int);
int SquareNumber(int x) {
return x * x;
}
int DoubleNumber(int x) {
return 2 * x;
}
int Run(PTRFUNC b, int n) {
static PTRFUNC func = b;
return b(func(n));
}
int main() {
cout << Run( DoubleNumber, SquareNumber(2) ) << " ";
cout << Run( SquareNumber, DoubleNumber(2) ) << endl;
}

Answer: 16 64_____________________________________________________________
4.

Explain briefly what the following program does?


#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char *argv[])
{
ifstream file(argv[1]);
if ( file ) {
file.seekg(0,ios::end);
cout << file.tellg() << endl;
file.close();
}
}

Answer: __The program prints out the size of a file (in bytes), which name is given as
a command line argument.__________________________________________________
5.

What does the following program output?


#include <vector>
#include <list>
int main()
{
vector<int> V(6);
for ( int i=0 ; i < 6 ; i++ )
V[i] = i + 1;
list<int> L;
for ( vector<int>::iterator it = V.begin(); it != V.end(); it++ ) {
if ( (*it % 2) == 1 )
L.push_front(*it);
}

for ( list<int>::iterator it = L.begin(); it != L.end(); it++ )


cout << *it << " ";

Answer: 5 3 1 ________________________________________________________

C++ Programming

Page 5 of 8

Dr R.K. Singla

Part III : Programming


1. In the following program the function findLocation returns the first location (index)

of a given element within an array. If the element is not found the array size (number of
elements) is instead returned. For example, the following program outputs: 1 4 2 .
#include <iostream>
#include "date.h"
int main()
{
int array_int[]
= { 5, 7, 4, 7 };
double array_double[] = { 4.5, 8.0, 7.5, 2.5 };
Date
array_date[]
= {Date(6,8,2002),Date(3,9,2002),Date(31,4,2002)};

cout << findLocation(


7, array_int, 4 ) << " ";
cout << findLocation( 8.5, array_double, 4 ) << " ";
cout << findLocation( Date(31,4,2002), array_date, 3 ) << " ";

a. Implement the findLocation function such that it works for both int and double data types
(as well as other types). Hint: use templates.
template<class T>
int findLocation(T elem, T arr[], int n)
{
for (int i = 0 ; i < n ; i++ )
{
if ( arr[i] == elem )
{
return i;
}
return n;
}

b. Modify the Date class declaration/definitions shown below such that an array of Date
objects also works with your findLocation function.
class Date {
public:
Date(int dd, int mm, int yyyy) : day(dd), month(mm), year(yyyy) {}
int getDay()
const { return day;
};
int getMonth() const { return month; };
int getYear() const { return year; };
bool operator==(const Date& D) const
{ return (D.day==day) && (D.month==month) && (D.year==year); }
private:
int day, month, year;
};

C++ Programming

Page 6 of 8

Dr R.K. Singla

2. Following is a declaration of an Array class. It works similar to a regular array


except that it additionally checks for subscript errors.
template<class T>
class Array
{
public:
Array(int n)

{ m_data = new int T [m_capacity = n]; }

Array(const Array<T>& arr) { /* definition not shown */ };


~Array()

{ delete [] m_data; }

Array<T>& operator=(const Array<T>& arr);


int& T& operator[](int index);
private:
int m_capacity;
int T *m_data;
};
template<class T>
int& T& Array<T> :: operator[](int index)
{

// Guard against subscript errors.


if ( index < 0 || index >= m_capacity ) {
cerr << "Array index out of range!" << endl;
exit(-1); // exit program
}
return m_data[index];

a. Make Array a template class capable of storing other basic data types (and objects). Write
your modifications directly into the above code (possibly changing the existing code).
b. In a program using the Array template class, how does one declare a char Array of size 5?
Answer: _Array<char> a(5)_________________________________________________
c. Implement the assignment operator for the Array class. Array assignment should be allowed
only if the capacity of the two arrays is the same; otherwise the program exits with an error
message (don't worry about templates here, assume the array elements are of type int ).
Array& Array :: operator=(const Array& A)
{
if ( this != &A ) {
if ( m_capacity == A.m_capacity ) {
// no need to delete m_data, same capacity.
m_capacity = A.m_capacity;
for ( int i=0 ; i < A.m_capacity ; i++ ) {
m_data[i] = A.m_data[i];
}
}
else {
cerr << "Array capacity mismatch in assignment!" << endl;
exit(-1); // exit program
}
}
return *this;
}

C++ Programming

Page 7 of 8

Dr R.K. Singla

The following program is given (not to be modified):


#include <iostream>
#include "exprNode.h" // The (Boolean) ExprNode
int
main()
{
// Create a tree for Boolean expression:
//
OR
//
/ \
//
AND
NOT
//
/
\
\
//
true false false
//
ExprNode *expr =
new OrNode( new AndNode( new ValueNode(true),
new ValueNode(false) ),
new NotNode( new ValueNode(false) ) );
cout << "Truth value of expression is: " << expr->eval() << endl;
}

delete expr;

// Delete the expression tree.

The program evaluates the truth-value of a Boolean expression represented as a syntax


(parse) tree, by calling the eval() method. The tree has four different types of expression
nodes (all derived from the ExprNode base class):
ValueNode:
NotNode:
AndNode:
OrNode:

stores a bool value (true/false)


represents the unary Boolean operator NOT
represents the binary Boolean operator AND
represents the binary Boolean operator OR

The declaration of the base class is provided (not to be modified). Your task is to write the
declarations / definitions of the derived classes.
////////////////// Abstract base class, do not modify ////////////////////
class ExprNode
{
public:
virtual bool eval() const = 0;
virtual ~ExprNode() { }
};
////////////////// VALUE node declaration / definitions //////////////////
class ValueNode : public ExprNode
{
public:
ValueNode(bool value) : m_value(value) { /* empty */ }
virtual bool eval() const { return m_value; }
virtual ~ValueNode() { /* empty */ };
private:
bool m_value;
};

C++ Programming

Page 8 of 8

Dr R.K. Singla

/////////////////// NOT node declaration / definitions ///////////////////


class NotNode : public ExprNode
{
public:
NotNode(ExprNode *expr) : m_expr(expr) { /* empty */ }
virtual bool eval() const { return !m_expr->eval(); }
virtual ~NotNode() { delete m_expr; }
private:
ExprNode* m_expr;
};

////////////////// AND node declaration / definitions ////////////////////


class AndNode : public ExprNode
{
public:
AndNode(ExprNode *left, ExprNode *right)
: m_left(left), m_right(right) { /* empty */ }
virtual bool eval() const
{ return m_left->eval() && m_right->eval(); }
virtual ~AndNode()
{ delete m_left;
delete m_right; }
private:
ExprNode *m_left;
ExprNode *m_right;
};

////////////////// OR node declaration / definitions ////////////////////


class OrNode : public ExprNode
{
public:
OrNode(ExprNode *left, ExprNode *right)
: m_left(left), m_right(right) { /* empty */ }
virtual bool eval() const
{ return m_left->eval() || m_right->eval(); }
virtual ~OrNode()
{ delete m_left;
delete m_right; }
private:
ExprNode *m_left;
ExprNode *m_right;
};

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy