Programming with C++ Test Answers



1. Which of the following operators cannot be overloaded?
Answers:
• +=
• >>
• <
• .
• ::
• &&
• =
• ?:

2. Which of the following statements about constructors and destructors are true?
Answers:
• In a given class, constructors are always required to be defined, but destructors are not
• Neither constructors nor destructors can take parameters
• Constructors can take parameters, but destructors cannot
• It is illegal to define a destructor as virtual
• It is illegal to define a constructor as virtual
• Both explicitly declared constructors and explicitly declared destructors are required in a class
3. Which of the following statements are true for operator overloading in C++?
Answers:
• The * operator can be overloaded to perform division
• The * operator can be overloaded to perform assignment
• ** can be overloaded to perform "to the power of"
• Operators can be overloaded only in inside classes
• Operators can be overloaded globally
4. Consider the sample code given below and answer the question that follows.

class X {
  int   i;

protected:
  float f;

public:
  char  c;
};

class Y : private X { }; 

Referring to the sample code above, which of the following data members of X are accessible from class Y
Answers:
• c
• f
• i
• None of the above
5. Consider the following code:

class Animal
{
private:
    int weight;

public:
    Animal()
    {
    }

    virtual void Speak()
    {
        cout << "Animal speaking";
    }
};

class Snake : public Animal
{
private:
    int length;

public:
    Snake()
    {
    }

    void Speak()
    {
        cout << "Snake speaking\r\n";
    }
};

int main()
{
    Animal *array = new Snake[10];

    for (int index= 0; index < 10; index++)
    {
        array->Speak();
        array++;
    }
   
    return 0;
}
What happens when the above code is compiled and executed?
Answers:
• The code will generate compilation errors
• The code will compile and run fine. "Animal speaking" will be printed to the output
• The code will compile and run fine. "Snake speaking" will be printed to the output
• The code will crash at runtime
6. Consider the sample code given below and answer the question that follows.

class A
{
public:
A() {}
~A()
{
cout << "in destructor" << endl;
}
};
void main()
{
A a;
a.~A();
}

How many times will "in destructor" be output when the above code is compiled and executed?
Answers:
• 0
• 1
• 2
• A compile time error will be generated because destructors cannot be called directly
7. Consider the sample code given below and answer the question that follows.

class Outer
{
  public:
    class Inner
      {
        int Count;
        public:
        Inner(){};
      };
};
int main()
  {
Inner innerObject;
Outer outObject;
return 0;
  }

What will be the result when the above code is compiled?
Answers:
• The code will compile fine
• There will be errors because classes cannot be defined inside other classes
• There will be an error because Outer does not define a constructor
• There will be an error because in the declaration of innerObject the type Inner must be qualified by Outer
• There will be no errors but a warning that Inner and Outer do not have destructors
8. Which of the following statements are FALSE with regard to destructors
Answers:
• A derived class can call the destructor of the parent class explicitly
• A class may have only one destructor
• Destructors cannot be invoked directly
• The return type for a destructor is void
• Destructors cannot accept arguments
9. Consider the sample code given below and answer the question that follows.

1 class Car
2 {
3 private:
4 int Wheels;
5
6 public:
7 Car(int wheels = 0)
8 : Wheels(wheels)
9 {
10 }
11
12 int GetWheels()
13 {
14 return Wheels;
15 }
16 };
17 main()
18 {
19 Car c(4);
20 cout << "No of wheels:" << c.GetWheels();
21 }

Which of the following lines from the sample code above are examples of data member definition?
Answers:
• 4
• 7
• 8
• 14
• 19
10. Consider the following statements relating to static member functions and choose the appropriate options:

1. They have external linkage
2. They do not have 'this' pointers
3. They can be declared as virtual
4. They can have the same name as a non-static function that has the same argument types
Answers:
• All are true
• Only 1, 2 and 4 are true
• Only 1 and 2 are true
• Only 1,3 and 4 are true
• All are false
11. What access specifier allows only the class or a derived class to access a data member
Answers:
• private
• protected
• default
• virtual
• public
12. Consider the line of code given below and answer the question that follows.

class screen;

Which of the following statements are true about the class declaration above?
Answers:
• Incorrect syntax. The body of the class declaration is missing
• Incorrect syntax. {}; is missing
• The syntax is correct
• Incorrect syntax. {} is missing
• Incorrect syntax. Requires a *
13. What will be the output of the following code?
class b
{
    int i;
    public:
    virtual void vfoo()
  {
    cout <<"Base ";
  }
};
class d1 : public b
{
    int j;
    public:
    void vfoo()
  {
    j++;
    cout <<"Derived";
  }
};
class d2 : public d1
{
    int k;
};
void main()
{
    b *p, ob;
    d2 ob2;
    p = &ob;
    p->vfoo();
    p = &ob2;
    p->vfoo();
}
Answers:
• Base Base
• Base Derived
• Derived Base
• Derived Derived
14. Consider the sample code given below and answer the question that follows.

class Shape
{
public:
virtual void draw() = 0;
};

class Rectangle: public Shape
{
public:
void draw()
{
// Code to draw rectangle
}
//Some more member functions.....
};

class Circle : public Shape
{
public:
void draw()
{
// Code to draw circle
}
//Some more member functions.....
};

int main()
{
Shape objShape;
objShape.draw();
}

What happens if the above program is compiled and executed?
Answers:
• Object objShape of Shape class will be created
• A compile time error will be generated because you cannot declare Shape objects
• A compile time error will be generated because you cannot call draw function of class 'Shape'
• A compile time error will be generated because the derived class's draw() function cannot override the base class draw() function
• None of the above
15. Which of the following is NOT a standard sorting algorithm:
Answers:
• std::sort
• std::qsort
• std::stable_sort
• std::partial_sort
16. Consider the sample code given below and answer the question that follows.

class Person
{
    string name;
    int age;
    Person *spouse;
public:
    Person(string sName);
    Person(string sName, int nAge);
    Person(const Person& p);

    Copy(Person *p);
    Copy(const Person &p);
    SetSpouse(Person *s);
};

Which one of the following are declarations for a copy constructor?
Answers:
• Person(string sName);
• Person(string sName, int nAge);
• Copy(Person *p);
• Person(const Person &p);
• Copy(const Person &p)?
17. Consider two classes A and B:

class A

{

private:

    int x;
    float y;

public:

friend class B;
};

class B

{
};

Which of the following is true?
Answers:
• A can access all private data members of B
• B can access all private data members of A
• A cannot access the private members of B
• B cannot access the private members of A
• Both A and B can access each other's private data members
18. Consider the following code:

class BaseException
{
   public:
   virtual void Output()
   {
      cout << "Base Exception" << endl;
   }
};

class DerivedException : public BaseException
{
   public:
   virtual void Output()
   {
      cout << "Derived Exception" << endl;
   }
};

void ExceptionTest()
{
   try
   {
      throw new DerivedException();
   }
   catch (DerivedException ex)
   {
      ex.Output();
   }
   catch (...)
   {
      cout << "Unknown Exception Thrown!" << endl;
   }
}

Invoking Exception Test will result in which output?
Answers:
• Base Exception
• Derived Exception
• Unknown Exception Thrown
• No Output will be generated
19. Which of the following statements are true about C++ vector class?
Answers:
• vector::empty deletes all elements of the vector
• vector::erase can be used to delete a single element and a range of elements of the vector
• After calling, vector::erase causes some of the iterators referencing the vector to become invalid
• vector::count returns the number of elements in the vector
• vector::size returns the number of elements in the vector
• vector::capacity returns the number of elements in the vector
20. Consider the following code:

class BaseException
{
public:
    virtual void Output()
    {
    cout << "Base Exception" << endl;
    }
};

class DerivedException : public BaseException
{
public:
    virtual void Output()
    {
    cout << "Derived Exception" << endl;
    }
};

void ExceptionTest()
{
    try
    {
          throw DerivedException();
    }
    catch (BaseException ex)
    {
          ex.Output();
    }
    catch (...)
    {
          cout << "Unknown Exception Thrown!" << endl;
    }
}

Invoking Exception Test will result in which output?
Answers:
• Base Exception
• Derived Exception
• Unknown Exception Thrown
• No Output will be generated
21. Which of the following statements are true?
Answers:
• Inline functions should be preferred over macros because inline functions have better performance
• Macro usage should be avoided because they are error prone
• Normal functions should be preferred over macros because normal functions have better performance
• Macro usage should be avoided because macros do not perform type checking
• Inline functions should be preferred over macros because inline functions perform type checking
22. Base class members are made accessible to a derived class and inaccessible to rest of the program by _____.
Answers:
• public access specifier
• private access specifier
• protected access specifier
• friend access specifier
23. Which of the following are NOT valid C++ casts
Answers:
• dynamic_cast
• reinterpret_cast
• static_cast
• const_cast
• void_cast
24. Sample Code

typedef char *monthTable[3];

Referring to the code above, which of the following choices creates two monthTable arrays and initializes one of the two?
Answers:
• monthTable(winter,spring={"March","April","May"});
• monthTable winter, spring;
• monthTable, winter, spring;
• monthTable, winter,spring={"March","April","May"};
• monthTable winter,spring={"March","April","May"};
25. Consider the sample code given below and answer the question that follows.

class Person
{
public:
   Person();
      virtual ~Person();
};
class Student : public Person
{
public:
   Student();
   ~Student();
};

main()
{
   Person *p = new Student();
   delete p;
}

Why is the keyword "virtual" added before the Person destructor?
Answers:
• To make it impossible for this particular destructor to be overloaded
• To ensure that correct destructor is called when p is deleted
• To ensure that the destructors are called in proper order
• To improve the speed of class Person's destruction
• To prevent the Person class from being instantiated directly making it an abstract base class
26. Consider the following code:

template<class T> void Kill(T *& objPtr)
{
   delete objPtr;
   objPtr = NULL;
}

class MyClass
{
};

void Test()
{
   MyClass *ptr = new MyClass();
   Kill(ptr);
   Kill(ptr);
}

Invoking Test() will cause which of the following?
Answers:
• Code will Crash or Throw and Exception
• Code will Execute, but there will be a memory leak
• Code will execute properly
• Code will exhibit undefined behavior
27. Consider the following class hierarchy:

class Base
{
}

class Derived : public Base
{
}

Which of the following are true?
Answers:
• The relationship between the Base and Derived can be described as: Base is a Derived
• The relationship between the Base and Derived can be described as: Base has a Derived
• Derived can access only public member functions of Base
• Derived can access public and protected member functions of Base
• The following line of code is valid: Base *object = new Derived();
28. What linkage specifier do you use in order to cause your C++ functions to have C linkage
Answers:
• extern "C"
• extern C
• _stdcall
• _cdecl
• _fastcall?
29. Which of the following techniques should you use to handle a destructor that fails?
Answers:
• Return an error code from the destructor
• Throw an exception from the destructor
• Write the error to a log file
• Use "delete this;" in the destructor
• None of the above
30. Which of the following techniques should you use to handle a constructor that fails?
Answers:
• Return an error code from the constructor
• Throw an exception from the constructor
• Write the error to a log file
• Use "delete this;" in the constructor
• None of the above
31. Which of the following statements about function overloading, is true?
Answers:
• C++ and namespaces should be used to replace occurrences of function overloading
• Overloaded functions may not be declared as "inline"
• Although the return types and parameter types of overloaded functions can be different, the actual number of parameters cannot change
• Function overloading is possible in both C and C++
• The parameter lists and const keyword are used to distinguish functions of the same name declared in the same scope
32. Consider the following code:

#include<stdio.h>

int main(int argc, char* argv[])
{
        enum Colors
        {
                red,
                blue,
                white = 5,
                yellow,
                green,
                pink
        };

        Colors color = green;
        printf("%d", color);
        return 0;
}

What will be the output when the above code is compiled and executed?
Answers:
• 4
• 5
• 6
• 7
• 8
• 9
• The code will have compile time errors
33. Consider the following code:

        class A {
              typedef int I;      // private member
              I f();
              friend I g(I);
              static I x;
          };

Which of the following are valid:
Answers:
• A::I A::f() { return 0; }
• A::I g(A::I p = A::x);
• A::I g(A::I p) { return 0; }
• A::I A::x = 0;
34. In the given sample Code, is the constructor definition valid?

class someclass
{
   int var1, var2;
   public:
      someclass(int num1, int num2) : var1(num1), var2(num2)
      {
      }
};
Answers:
• Yes, it is valid
• No, we cannot assign values like this
• No, the parenthesis cannot be empty
• No, var1 and var2 are not functions but are variables
35. Consider the following code:

class BaseException
{
public:
   virtual void Output()
   {
      cout << "Base Exception" << endl;
   }
};

class DerivedException : public BaseException
{
public:
   virtual void Output()
   {
      cout << "Derived Exception" << endl;
   }
};

void ExceptionTest()
{
   try
   {
      throw DerivedException();
   }
   catch (BaseException& ex)
   {
      ex.Output();
   }
   catch (...)
   {
      cout << "Unknown Exception Thrown!" << endl;
   }
}

Invoking Exception Test will result in which output?
Answers:
• Base Exception
• Derived Exception
• Unknown Exception Thrown
• No Output will be generated
36. Consider the following code:

#define SQ(a) (a*a)

int  answer = SQ(2 + 3);

What will be the value of answer after the above code executes?
Answers:
• 10
• 11
• 25
• 13
• None of the above
37. Consider the following class hierarchy:

class Base
{
}

class Derived : private Base
{
}

Which of the following are true?
Answers:
• The relation between Base and Derived can be described as: Base is a Derived
• The relation between Base and Derived can be described as: Base has a Derived
• Derived can access private member functions of Base
• Derived can access public and protected member functions of Base
38. Consider the sample code given below and answer the question that follows:

char **foo;
/* Missing code goes here */
for(int i = 0; i < 200; i++)
{
foo[i] = new char[100];
}

Referring to the sample code above, what is the missing line of code?
Answers:
• foo = new *char[200];
• foo = new char[200];
• foo = new char[200]*;
• foo = new char*[200];
• foo = new char[][200];
39. What will be the output of the following code?

class A
{
public:
      A():pData(0){}
      ~A(){}
      int operator ++()
      {
            pData++;
            cout << "In first ";
            return pData;
      }
      int operator ++(int)
      {
            pData++;
            cout << "In second ";
            return pData;
      }
private:
      int pData;
};
void main()
{
     A a;
     cout << a++;
     cout << ++a;
}
Answers:
• In first 1 In second 2
• In second 1 In first 2
• In first 0 In second 2
• In second 0 In first 2
40. Which of the following are true about class member functions and constructors?
Answers:
• A constructor can return values but a member function cannot
• A member function can declare local variables but a constructor cannot
• A member function can return values but a constructor cannot
• A constructor can declare local variables but a member function cannot
• A member function can throw exceptions but a constructor cannot
41. How many arguments can be passed to an overloaded binary operator?
Answers:
• 4
• 3
• 2
• 1
• 0
42. What will happen when the following code is compiled and executed?

#include<iostream>
using namespace std;

class myclass
{
private:
    int number;
public:
    myclass()
    {
        number = 2;
    }
    int &a()
    {
        return number;
    }
};

int main()
{
    myclass m1,m2;
    m1.a() = 5;
    m2.a() = m1.a();
    cout << m2.a();
    return 0;
}
Answers:
• Compile time errors will be generated because right hand side of expressions cannot be functions
• The printed output will be 5
• The printed output will be 2
• The printed output will be undefined
43. You want the data member of a class to be accessed only by itself and by the class derived from it. Which access specifier will you give to the data member?
Answers:
• Public
• Private
• Protected
• Friend
• Either Public or Friend
44. If input and output operations have to be performed on a file, an object of the _______ class should be created.
Answers:
• fstream
• iostream
• ostream
• istream
• None
45. State which of the following is true.
Answers:
• Function templates in C++ are used to create a set of functions that apply the same algorithm to different data types
• Classes in C++ are used to develop a set of type-safe classes
• C++ is useful for developing collection classes
• C++ is useful for developing smart pointers
• All of the above
46. Consider the sample code given below and answer the question that follows.

class SomeClass
{
int x;
public:
SomeClass (int xx) : x(xx) {}
};
SomeClass x(10);
SomeClass y(x);

What is wrong with the sample code above?
Answers:
• SomeClass y(x); will generate an error because SomeClass has no copy constructor
• SomeClass y(x); will generate an error because SomeClass has no default constructor
• SomeClass y(x); will generate an error because SomeClass has no public copy constructor
• x(xx) will generate an error because it is illegal to initialize an int with that syntax
• The code will compile without errors
47. Which of the following statements regarding functions are false?
Answers:
• Functions can be overloaded
• Functions can return the type void
• Inline functions are expanded during compile time to avoid invocation overhead
• You can create arrays of functions
• You can pass values to functions by reference arguments
• You can return values from functions by reference arguments
• A function can return a pointer
48. State whether True or False.

Unary operator overloaded by means of a friend function takes one reference argument.
Answers:
• True
• False
49. What does ADT stand for?
Answers:
• Accessible derived type
• Access to derived type
• Abstract data type
• Abstract derived type
• Accessible data type
50. A pure virtual function can be declared by _______.
Answers:
• equating it to 1
• equating it to 0
• equating it to NULL
• the 'pure' keyword
• the 'abstract' keyword
51. Which of the following are true about class and struct in C++:
Answers:
• A class can have destructor but a struct cannot
• A class can have inheritance but a struct cannot
• In a class all members are public by default, whereas in struct all members are private by default
• In a class all members are private by default, whereas in struct all members are public by default
52. What is the output of the following code segment?
int n = 9;
int *p;
p=&n;
n++;
cout << *p+2 << "," << n;
Answers:
• 11,9
• 9,10
• 12,10
• 11,10
53. What will be the output of the following code?

#include<iostream>
using namespace std;

class b
{
int i;
public:
void vfoo()
{ cout <<"In Base "; }
};

class d : public b
{
int j;
public:
void vfoo()
{
cout<<"In Derived ";
}
};

void main()
{
b *p, ob;
d ob2;
p = &ob;
p->vfoo();
p = &ob2;
p->vfoo();
ob2.vfoo();
}
Answers:
• In Base In Base In Derived
• In Base In Derived In Derived
• In Derived In Derived In Derived
• In Derived In Base In Derived
• In Base In Base In Base
54. Which of the following sets of functions do not qualify as overloaded functions?
Answers:
• void fun(int, char *) void fun(char *,int)
• void x(int,char) int *x(int,char)
• int get(int) int get(int,int)
• void F(int *) void F(float *)
• All of the above are overloaded functions
55. Consider the sample code given below and answer the question that follows.

template <class T> Run(T process);

Which one of the following is an example of the sample code given above?
Answers:
• A non-template member function
• A template function definition
• A template function declaration
• A template class definition
• A template class declaration
56. Suppose MyClass is a class that defines a copy constructor and overloads the assignment operator. In which of the following cases will the copy constructor of MyClass be called?
Answers:
• When an object of MyClass is passed by value to a function
• When an object of MyClass is returned by value from a function
• MyClass object1; MyClass object2; object2 = object1;
• MyClass object1; MyClass *object2 = new MyClass(object1);
• MyClass object1; MyClass object2 = object1;
57. Which of the following STL classes is deprecated (ie should no longer be used)
Answers:
• ostrstream
• ostringstream
• ostream
• wostream
58. Which of the following is a  function that returns a non zero value to indicate an I/O stream error?
Answers:
• bad
• good
• fail
• eof
• err
• error
• filerror
• None of the above
59. Consider the following code:

#include<iostream>
using namespace std;

class A
{
public:
  A()
  {
    cout << "Constructor of A\n";
  };
  ~A()
  {
    cout << "Destructor of A\n";
  };
};

class B
{
public:
  B()
  {
    cout << "Constructor of B\n";
  };
  ~B()
  {
    cout << "Destructor of B\n";
  };
};

class C
{
public:
  A objA;
  B objB;
};

int main()
{
  C *pC;
  pC = new C();
  delete pC;
  return 0;
}

What will be the printed output?
Answers:
• Constructor of B Constructor of A Destructor of A Destructor of B
• Constructor of A Constructor of B Destructor of B Destructor of A
• Constructor of B Constructor of A Destructor of B Destructor of A
• Constructor of A Constructor of B Destructor of A Destructor of B
• The sequence of construction and destruction of A and B will be compiler specific
60. Which of the following is not a standard STL header?
Answers:
• <array>
• <deque>
• <queue>
• <list>
61. Which of the following member functions can be used to add an element in an std::vector?
Answers:
• add
• front
• push
• push_back
62. Which of the following is a predefined object in C++ and used to insert to the standard error output?
Answers:
• std::err
• std::error
• std::cerror
• std::cerr
• std::cin
• std::clog
63. Consider the following code:

#include<iostream>
using namespace std;

int main()
{
cout << "The value of __LINE__ is " <<__LINE__;

return 0;
}

What will be the result when the above code is compiled and executed?
Answers:
• The compilation will fail with the error - '__LINE__' : undeclared identifier
• The compilation will fail with the error - '__LINE__' unresolved identifier
• The code will compile and run without errors
• The code will crash at runtime
64. In C++, the keyword auto can be used for:
Answers:
• Automatic assignment of data to objects during instantiation
• Automatic call of a function
• Declaration of a local variable
• Automatically erasing an object when it is no longer needed
• Automatic handling of run-time errors in the program
• Automatic termination of a program in case the user does not respond within a given time period
• Automatic creation of variables
65. If a matching catch handler (or ellipsis catch handler) cannot be found for the current exception, then the following predefined runtime function is called ______.
Answers:
• abort
• set_terminate
• terminate
• close