All Ass Answers
All Ass Answers
Total Marks : 20
Question 1
Which special symbol allowed in a variable name? Mark 1
a) !
b) |
c) *
d) _
Answer: d)
Explanation: As per the Syntax of the language. Refer Slides
Question 2
Which of the following are unary operators in C? Mark 1
a) ?:
b) ++
c) *=
d) sizeof()
Answer: b) d)
Explanation: As per the Syntax of the language. Refer Slides
Question 3
Which of the following declarations are correct? Mark 1
a) struct mystruct {int a;};
b) struct {int a;}
c) struct mystruct {int a;}
d) struct mystruct int a;
Answer: a)
Explanation: As per the Syntax of the language. Refer Slides.
1
Question 4
What will the function Sum return? Mark 1
c) Compilation Error: return value type does not match the function type
Answer: c)
Explanation: The return type of the function is void, hence an integer value cannot be
returned.
Question 5
What value will be printed for data.c? Marks 2
#include<stdio.h>
#include <string.h>
int main() {
union Data {
int i;
unsigned char c;
} data;
data.c =’C’;
data.i = 89;
printf( "%c\n", data.c);
return 0;
}
a) C
b) Y: ASCII 89
c) G
d) C89
Answer: b)
Explanation: When %c is used for printing an integer value, conversion to the equivalent
ASCII
2
Question 6
What is the output of the above program? Marks 2
#include <stdio.h>
void foo( int[] );
int main() {
int myarray[4] = {1, 2, 3, 0};
foo(myarray);
printf("%d ", myarray[0]);
}
void foo(int p[4]){
int k = 34;
p = &k;
printf("%d ", p[0]);
}
a) 1 2
b) 1 3
d) 34 1
Answer: d)
Explanation: The base pointer of the array is used to point to an integer 34. In main, the
array is accesssed directly to print the 1st element.
Question 7
What is the output of the following program? Marks 2
#include <stdio.h>
#define func(x, y) x / y + x
int main() {
int i = -6, j = 3;
printf("%d\n",func(i + j, 3));
return 0;
}
b) -4
c) -8
d) 3
Answer: c)
Explanation: x/y+x replaced by i + j/3 + i + j i.e (-6 + 3/3 -6 +3) = (-6 + 1 -6 +3) = -8
3
Question 8
What will be the output of the following program? Marks 2
#include <stdio.h>
int sum(int a, int b, int c) {
return a + b + c / 2;
}
void main() {
int (*function_pointer)(int, int, int);
function_pointer = sum;
printf("%d", function_pointer(2, 3, 4));
}
b) 7
c) 4.5
d) 5.5
Answer: b)
Explanation: function pointer is a pointer defined for any function with 3 integer parameters
and integer return type. It points to function sum and returns the result of the sum.
Question 9
Fill in the blank to concatenate strings str1 and str2 to form str3? Marks 2
#include <iostream>
#include <string>
using namespace std;
int main(void) {
string str1 = "I ";
string str2 = "Travel";
a) str1+str2
b) strcat(str1,str2);
c) strcat(strcpy(str3,str1),str2);
d) str1.append(str2)
4
Question 10
What will be the output of the following program? Marks 2
#include <iostream>
#include <algorithm>
using namespace std;
bool srt (int i, int j) {
return (i < j);
}
int main() {
int data[] = {52, 76, 19, 5, 10, 100, 56, 98, 17};
sort (data + 1, data + 4, srt);
for (int i = 0; i < 9; i++)
cout << data[i] << " ";
return 0;
}
a) 52 5 19 76 10 100 56 98 17
b) 52 76 19 10 5 100 56 98 17
c) 76 5 10 19 76 100 56 98 17
d) 76 5 10 19 76
Answer: a)
Explanation: The whole array is not passed for sorting, only from index 1 (data + 1, i.e 0
+ 1) to index 4 (data + 4, i.e 0 + 4), i. e 3 elements, 76, 19, 5
Question 11
What will be the output of the following program? Marks 2
#include<iostream>
#include<string.h>
#include<stack>
using namespace std;
int main() {
char str[19]= "Programming";
stack<char> s;
for(int i = 0; i < strlen(str); i++)
s.push(str[i]);
for(int i = 0; i < strlen(str) - 1; i++) {
cout << s.top();
s.pop();
}
return 0;
}
a) rogramming
b) ogramming
c) gnimmargor
5
d) gnigormmar
Answer: c)
Explanation: When programming pushed to stack, the element on the top is g (gnimmar-
gorp) , which is displayed and then popped. Continues till length of str - 1, hence p not printed
at the end.
Question 12
Fill up the blanks for A# and B# below: Marks 2
#include <iostream>
#include <vector>
using namespace std;
int main() {
cout << "Enter the no. of elements: ";
int count, j, sum=0;
cin >> count;
__________________ A# // Declare with Default size
__________________ B# // Change the size to the required amount
for(int i = 0; i < arr.size(); i++) {
arr[i] = i;
sum + = arr[i];
}
cout << "Array Sum: " << sum << endl;
return 0;
}
Answer: d)
Explanation: As per syntax, using resize operator
6
Programming in C++: Assignment Week 2
Total Marks : 20
Each question carries one mark
Right hand side of each question shows its Type (MCQ/MSQ)
March 3, 2017
Question 1
• Look at the code snippet below:
Which of the following statement is true for the variable ’p’ ? Mark 1
a. const-Pointer to non-const-Pointee
b. non-const-Pointer to const-Pointee
c. const-Pointer to const-Pointee
d. non-const-Pointer to non-const-Pointee
Answer: a
Explanation: As per syntax, refer slides
Question 2
• Look at the following code segment and decide which statement(s) is/are correct. Mark
1
int main(){
int m = 4;
const int n = 5;
const int * p = &n;
int * const q = &m;
// ...
n = 6; // stmt-1
*p = 7; // stmt-2
p = &m; // stmt-3
*q = 8; // stmt-4
q = &n; // stmt-5
// ...
}
a. stmt-1
b. stmt-2
c. stmt-3
d. stmt-4
1
e. stmt-5
Answer: c, d
Explanation: As per syntax, refer slides
Question 3
• Identify the output of the following code. Mark 1 Mark 1
#include<iostream>
using namespace std;
int main() {
a. 5.9
b. Cannot assign an integer value to a double variable
c. 5.90
d. Cannot assign value 5.9 to read only c.re
Answer: d
Explanation: c is variable of the structure Complex, but it is defined as const,
hence cannot be modified
Question 4
• Identify the correct statement(s). Mark 1
#include <iostream>
#include <cmath>
using namespace std;
#define TWO 2
#define PI 4.0*atan(1.0)
int main() {
int r = 10;
double peri = TWO * PI * r;
cout << "Perimeter = "
<< peri << endl;
return 0;
}
2
d. TWO and PI look like variables
Answer: b), d)
Explanation: TWO and PI are manifest constants, hence types can be indeter-
minate and look like variables.
3
Question 5
• What will be the output of the following code? Mark 1
#include <iostream>
using namespace std;
double Ref_const(const double ¶m) {
return (param * 3.14);
}
int main() {
double x = 8, y;
y = Ref_const(x);
cout << x << " "<< y;
return 0;
}
Question 6
• What will be the output of the following code? Mark 1
#include <iostream>
using namespace std;
void func(int n1 = 10, int n2) {
cout <<n1 << " "<< n2;
}
int main() {
func(1);
func(3, 4);
return 0;
}
a. 1 10 3 4
b. 10 1 4 3
c. 10 1 3 4
d. Compilation error: Argument missing for parameter 2 of func
Answer: d)
Explanation: Default values needs to specified from the end, hence function
resoultion fails
4
Question 7
• What will be the output of the following code? Mark 1
#include <iostream>
using namespace std;
int Add(int a, int b) { return (a + b); }
double Add(double c) {
return (c + 1);
}
int main() {
int x = 1, y = 2, z;
z = Add(x, y);
cout << z;
double s = 4.5, u;
u = Add(s);
Question 8
• Which function prototype will match the function call func(3.6,7)? Mark 1
a. Proto 1
b. Proto 2
c. Proto 3
d. Proto 4
Answer: a), b), c)
Explanation: Proto 1 allowed, as 3.6(1st parameter) is downcast to integer.
Proto 2 allowed, as default value will be used for third parameter. Proto 3 allowed,
default value and type will be used for third parameter. Proto 4 fils for mismatch
in 2nd parameter
5
Question 9
• What will be the output of the following code? Mark 1
#include<iostream>
using namespace std;
int main() {
int *ptr = NULL;
cout << " Output: In Program";
delete ptr;
return 0;
}
Question 10
• Fill up the blanks to get the desired output according to the test cases. Mark 1
#include <iostream>
#include <cstring>
#include <cstdlib>
using namespace std;
typedef struct _String { char *str; } String;
____________________________________ {
String s;
s.str = (char *) malloc(strlen(s1.str) +
strlen(s2.str) + 1);
strcpy(s.str, s1.str);
strcat(s.str, s2.str);
return s;
}
int main() {
String s1, s2, s3;
s1.str = strdup("I");
s2.str = strdup(" love Travelling ");
s3 = s1 + s2;
6
b. String +(const String& s1, const String& s2)
c. String operator+(const String& s1, const String& s2)
d. string operator+(const String s1, const String& s2)
Answer: c)
Explanation: As per syntax, Overloading operator + for String structure. Ref-
erence parameters passed as const to prevent modification.
I Programming Assignments
Question 1
• Fill up the blanks by providing appropriate return type and argument type for the
function Ref func() to get the desired output according to the test cases. Marks 2
#include <iostream>
using namespace std;
_____ Ref_func( _____ param) {
return (++param);
}
int main() {
int x, y, z;
cin >> x ;
cin >> y ;
y = Ref_func(x);
cout << x << " "<< y << endl;
Ref_func(x) = z;
cout << x << " "<< y;
return 0;
}
Input: 8, -9
Output: 9 9
-9 9
Input: 10, 20
Output: 11 11
20 11
Input: -19, -32
Output: -18 -18
-32 -18
7
Question 2
• Fill up the blanks to get the desired output according to the test cases. Marks 2
#include <stdio.h>
int func(int, int);
#define func(x, y) __ / __ + ___ // Complete the Macro definition
int main() {
int i,j;
scanf("%d", &i);
scanf("%d", &j);
printf("%d ",func(i + j, 3));
______ func // Fill the blank
printf("%d\n",func(i + j, 3));
}
int func(int x, int y) {
return x / y + x;
}
Question 3
• Fill up the blanks with appropriate keyword to get the desired output according to the
test cases. Marks 2
#include <iostream>
using namespace std;
______ int SQUARE(int x) { ______ x * x; }
int main() {
int a , b, c;
cin >> a ;
b = SQUARE(a);
cout << "Square = " << b << ", ";
c = SQUARE(++a);
cout << "++ Square = " << c ;
return 0;
}
8
Question 4
• Fill up the blanks to get the desired output according to the test cases in the perspective
of dynamic memory allocation and de-allocation. Marks 2
#include <iostream>
using namespace std;
int main(){
int d;
____________________ // use operator new to allocate memory to variable ’p’
cin>> d ;
*p = d ;
cout << ++*p + d++ * (++*p + *p);
__________delete(___); // Fill the blank
return 0;
}
a. Input: -7 Output: 64
b. Input: 11.5 Output: 298
c. Input: 15 Output: 526
Question 5
• Overload the function ’Area’, by writing the appropriate definition in place of blank to
get the desired output according to the test cases. Marks 2
include<iostream>
using namespace std;
___________________________ // Overload the function ’Area’
___________________________ // Write the definition of ’Area’
int main() {
int x ,y, t;
double z, u, f;
t = Area(x);
cout << "Area = " << t << " ";
f = Area(z);
cout << "Area = " << f << " ";
f = Area(z,u);
cout << "Area = " << f ;
return 0;
}
9
c. Input: 7, 8, 7, 9.6 Output: Area =70 Area =70 Area =67.2
10
Programming in C++: Assignment Week 3
Total Marks : 20
Question 1
What is the output of the sizeof operator? (Assume sizeof(int) = 4) Mark 1
#include<iostream>
using namespace std;
class Test {
int x_;
unsigned char str[8];
};
int main() {
Test t;
cout << sizeof(t) << " ";
}
a) 10
b) 12
d) Default size: 0
Answer: b)
Explanation: Sum of memory requirements for all the data members
Question 2
What will be the output of the program? Mark 1
#include<iostream>
using namespace std;
class Test {
int x_;
int y_;
};
int main() {
1
Test.x_ = 1;
cout << Test.x_;
}
a) 1
b) Default value
c) Compilation Error: Cannot modify read only variable
d) 0
Answer: c)
Explanation: Object not created, Invalid access of data member x with class name.
Question 3
What is the output of the program? Mark 1
#include<iostream>
using namespace std;
class Test {
int x_;
int y_;
void func() {
x_ = y_ = 1;
cout << x_ << " " << y_;
}
};
int main() {
Test t;
t.func();
}
a) 1 1
b) x = 1 y = 1
c) Compilation error: Cannot access private member
d) None of the above
Answer: c)
Explanation: func() is a private member function, hence cannot be accessed outside class
Question 4
Consider Object S of class Sample. What is the type of this pointer? Mark 1
a) S * const this
b) S const * const this
c) S * this
d) const S const * this
Answer: a)
Explanation: As per syntax, refer slides
2
Question 5
Which functions will change the state of the object of class Test? Mark 1
#include<iostream>
using namespace std;
class Test {
int x_;
int y_;
public:
void print() { cout << x_ << " " << y_; }
void setx(int m_) {
x_ = m_;
}
void sety(int n_) {
y_ = n_;
}
int calc1(int n_) {
int t;
t = n_ * x_ * y_;
x_ = n_ * 3;
return t;
}
void calc2(int n_) {
int t;
t = n_ * x_;
cout << t;
}
};
b) Only print()
Answer: d)
Explanation: The state of a class is the collection of values of all the member variables of a
class at a point. setx(), calc1() and sety() modifies the values of the member variables of the
class. Refer slides
3
Question 6
Consider the program below. An implementation of class Test is shown along with an appli-
cation section using object of Test. Mark 1
4
t = n_ * x_[0];
cout << t;
}
};
b) No change required
Answer: b)
Explanation: The implementation of the private members of the class is changed, but it
did not change the interface of the class. The implementation is not visible outside the class.
5
Question 7
Consider class Test. What are the permissible signatures of a Copy Constructor? Marks 1
Answer: d)
Explanation: As per syntax, refer slides
Question 8
What will be the output of the following program? Mark 1
#include<iostream>
using namespace std;
class Sample{
int x;
int y;
public:
void setx(int n) { x = n; }
void sety(int m) { y = m; }
int gety() { return y;}
int getx() { return x; }
};
class Experiment {
public:
display(Sample t) { t.setx(8);
cout << t.x;
}
};
int main() {
Sample t;
Experiment e;
e.display(t);
}
a) 8
b) Compilation Error: setx() method of class Sample cannot be accessed in class Experiment
c) 8 8
Answer: d)
Explanation: Private data members of a class cannot be accessed by other classes or global
functions.
6
Question 9
What will be the output of the program? Mark 1
#include <iostream>
#include <string>
using namespace std;
class Sample {
string name;
public:
Sample(string s): name(s) {
cout << name << " Created" << " ";
}
~Sample() {
cout << name << " Destroyed" << " ";
}
};
int main() {
Sample * s1 = new Sample("s1");
Sample * s2 = new Sample("s2");
return 0;
}
d) s1 Created s2 Created
Answer: d)
Explanation: s1 and s2 created by new operator, delete operator should be used to call the
destructor, as in this case the destructor is not called implicitly.
7
Question 10
Identify the correct statement(s). Mark 1
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
string name, addr;
const int id;
string dob;
int main() {
const Employee e1("Ram", "Kolkata", "12-02-02", count++);
e1.print_attr_dob();
e1.print_attr_name();
return 0;
}
b) Compilation Error: cannot convert ’this’ pointer from ’const Employee’ to ’Employee &’
for print attr dob()
c) Compilation Error: cannot convert ’this’ pointer from ’const Employee’ to ’Employee &’
for print attr name()
d) B and C
Answer: a), c)
Explanation: A constant object cannot invoke a non constant member function. Constant
data member, id cannot be modified in the member function print attr dob
8
I Programming Assignment
Question 1
Write the required syntax for the constructor and copy constructor to get the output as per
the test cases. Marks 2
#include <iostream>
using namespace std;
class Complex {
public: double *re, *im;
Complex(__________________) {
re = new double(r);
im = new double(m);
}
Complex(________________ ){
re = new double; im = new double;
*re = *t.re; *im= *t.im;
}
~Complex(){
delete re, im;
}
};
int main() {
double x, y, z;
9
Question 2
Write the required syntax for the constructor to get the output as per the test cases. Marks 2
#include <iostream>
using namespace std;
class Sample {
public:
int data_, graph_;
char data_or_graph_;
Sample(___________________________________): ____________________________{
cout << data_ << " " << data_or_graph_<< " " << graph_ <<" "<<endl;
}
};
int main() {
int x; char y;
cin>>x >> y ;
return 0;
}
Answer: int x = 5, char z = ’B’, int y = 6 // data (x), data or graph (z), graph (y)
Explanation: : Evaluation of S3 gives 5, B, 6, hence we get the default values. The rest of
the syntax is as per slides.
a. Input: 4 D Output: 4 D 6 3 E 6 5 B 6
b. Input: 3 E Output: 3 E 6 2 F 6 5 B 6
Question 3
Write the required constructor and function definitions of the class Stack to get the output as
per the test cases. Marks 2
#include <iostream>
#include <vector>
#include<string.h>
using namespace std;
class Stack {
_____________________: // Write the appropriate Access specifier
vector<char> data_; int top_;
public:
int empty() { ________________________; }
void push(char x) { _________________________;}
void pop() { _______________; }
char top() { __________________; }
};
int main() {
Stack s;
10
char str[20];
s.data_.resize(100);
s.top_ = -1;
for(int i = 0; i < strlen(str) - 1; ++i)
s.push(str[i]);
while (!s.empty()) {
cout << s.top(); s.pop();
}
return 0;
}
Answer: public // return (top == -1) // data [++top ] = x // –top // return data [top ]
Explanation: Access specifier will be public as the data members are accessed outside class.
The functions are standard stack functions, refer slides
Question 4
Look into the main() function write the proper constructor by filling the blank to get the
output as per the test cases. Marks 2
#include <iostream>
#include <cmath>
using namespace std;
class Complex { private: double re_, im_;
public:
Complex(__________________________________): re_(re), im_(im)
{ cout << "Ctor: (" << re_ << ", " << im_ << ")" << endl; }
~Complex()
{ cout << "Dtor: (" << re_ << ", " << im_ << ")" << endl; }
void print() { cout << "|" << re_ << "+j" << im_ << "| " << endl; }
};
Complex c(7.2, 4);
int main() {
cout << "main" << endl;
double x, y;
cin >> x;
cin >> y;
Complex d(x); Complex e;
c.print();
d.print();
return 0;
}
11
Answer: double re = 0.0, double im = 0.0
Explanation: The default value of the double parameters of the constructor Complex will
be 0.0,0.0 as it is evaluated so in case of Complex e call
Output:
Ctor: (7.2, 4)
main
Ctor: (4.5, 0)
Ctor: (0, 0)
|7.2+j4|
|4.5+j0|
Dtor: (0, 0)
Dtor: (4.5, 0)
Dtor: (7.2, 4)
b. Input: 5.6, 4;
Output:
Ctor: (7.2, 4)
main
Ctor: (5.6, 0)
Ctor: (0, 0)
|7.2+j4|
|5.6+j0|
Dtor: (0, 0)
Dtor: (5.6, 0)
Dtor: (7.2, 4)
c. Input: 0, 0 ;
Output:
Ctor: (7.2, 4)
main
Ctor: (0, 0)
Ctor: (0, 0)
|7.2+j4|
|0+j0|
Dtor: (0, 0)
Dtor: (0, 0)
Dtor: (7.2, 4)
Question 5
The program indicates the concept of mutability . Fill the blank with appropriate kew word
to satisfy the given test casesMarks 2
#include <iostream>
using namespace std;
class MyClass {
int mem_;
12
_____________ int x_;
public:
MyClass(int m, int mm) : mem_(m), x_(mm) {}
int getMem() const { return mem_; }
void setMem(int i) { mem_ = i; }
int getxMem() ________ { return x_; }
void setxMem(int i) __________ { x_ = i; }
};
int main() {
int x, y,z;
cin >> x;
cin >> y;
cin >> z;
const MyClass myConstObj(x, y);
myConstObj.setxMem(z);
cout << myConstObj.getxMem() << endl;
return 0;
}
a. Input: 4, 5, 6 ; Output: 6
b. Input: 1, 1, 0 ; Output: 0
13
Programming in C++: Assignment Week 5
Total Marks : 20
April 3, 2017
Question 1
Look at the code snippet bellow. Find out the sequence in which the function area() associated
with Rectangle & Triangle class will be called. Mark 1
class Polygon {
protected:
int width, height;
public:
void set_values (int a, int b)
{ width=a; height=b;}
};
int main () {
Rectangle rect;
Triangle trgl;
rect.set_values (6,5);
trgl.set_values (6,5);
rect.area() ;
trgl.area() ;
return 0;
}
a) Area-2, Area-1
1
b) Area-1, Area-1
c) Area-1, Area-2
d) Area-2, Area-2
Answer: c)
Solution: By the order of calling functions
Question 2
Which of the following function will be invoked by d.func(1)? Mark 1
#include <iostream>
using namespace std;
int main() {
Derived d;
d.func(1);
return 0;
}
a) Base::func(int)
b) Derived::func(int)
c) Compilation Error
Question 3
Find out the out put of the following Program.
#include <iostream>
using namespace std;
class Animal {
public:
int legs = 4;
};
2
class Dog : public Animal {
public:
int tail = 1;
};
int main() {
Dog d;
cout << d.legs;
cout << d.tail;
return 0;
}
a) 1 4
d) 4 1
Question 4
Look at the code snippet bellow. Find out, which of the show() function will be called by
calling b->show(). Mark 1
class Base {
public:
void show() { }
};
class Derived :public Base {
public:
void show() { }
};
int main() {
Base* b; //Base class pointer
Derived d; //Derived class object
b = &d;
b->show();
return 0;
}
Answer: a)
Solution: Early Binding Occurs
3
Question 5
Look at the code snippet bellow. Find out, which of the show() function will be called by
calling b->show() ? Mark 1
class Base {
public:
virtual void show() { cout << "Base class"; }
};
class Derived :public Base {
public:
void show() { cout << "Derived Class"; }
};
int main() {
Base* b; //Base class pointer
Derived d; //Derived class object
b = &d;
b->show();
return 0;
}
Answer: b)
Solution: Late Binding Occurs as show() is virtual
Question 6
What will be the output of the following Code snippet? Mark 1
class B {
public:
B() { cout << "B "; }
~B() { cout << "~B "; }
};
class C : public B {
public:
C() { cout << "C "; }
~C() { cout << "~C "; }
};
class D : private C {
B data_;
public:
D() { cout << "D " << endl; }
~D() { cout << "~D "; }
};
int main() {
4
{D d; }
return 0;
}
a) B C B C D ˜D ˜C ˜B ˜C ˜B
b) B C B D ˜D ˜B ˜C ˜B
c) B D B C ˜C ˜B ˜D ˜B
d) B C B C ˜C ˜B ˜C ˜B
Question 7
Identify the correct statements? Mark 1
class base {
public:
int x;
protected:
int y;
private:
int z;
};
a) 1, 3 & 5
b) 2, 4 & 6
c) 6, 8 & 9
5
d) 2, 6 & 7
Answer: d)
Solution: By definition of public, private and protected inheritance
Question 8
Which lines of the following program will not compile? Mark 1
d.var_ = 1; // ---14
d.varD_ = 1; // ---15
return 0; // ---17
} // ---18
a) 6, 10, 14, 15
b) 6, 15
c) 4, 14, 16
d) 6, 14, 16
Answer: c)
Solution: Can’t access protected data member
Question 9
Consider the following code snippet. Which of the following statement is true, when t.getX()
is called ? Mark 1
class Test {
int x;
public:
Test(int a):x(a){}
6
virtual void show() = 0;
int getX() { /* Function definition */ }
};
int main(void){
Test t(5);
t.getX();
return 0;
}
d) b & c
Answer: b)
Solution: Can’t create object of a abstract class
Question 10
What will be the output of the following program? Marks 1
#include<iostream>
using namespace std;
class Shape {
public:
int x, y;
void draw()
{ Shape::draw(); cout << w << " " << h ; }
};
int main() {
Rectangle *r = new Rectangle(1,2);
r-> draw();
return 0;
}
7
a) 0 0 1 2
b) 7 8 1 2
c) 7 8 5 6
d) 0 0 5 6
Answer: b)
Solution: Shape(7, 8) initialize x and y as 7 and 8. Rectangle(1,2) initialize w and h as 1 and
2.
Programming Questions
Question 1
Consider the skeletal code given below and Fill the blank or remove the blank in the header
of the functions to match the output for the given input. Marks 2
#include <iostream>
using namespace std;
class Shape {
protected:
float l;
public:
void getData(){ cin >> l; }
return l*l;
}
};
int main()
{
Shape * b; //Base class pointer
Circle d; //Derived class object
b = &d;
b->getData();
cout << b->calculateArea();
return 0;
}
8
a. Input: 5
Output: 78.5
b. Input: 28
Output: 2461.76
c. Input: 45
Output: 6358.5
Answer: virtual
Solution: Derived class function is called using a base class pointer. virtual function is resolved
late, at runtime.
Question 2
Consider the skeletal code given below.Fill up the blank by following the instructions associated
with each blank and complete the code, So that the output of the test cases would match Marks:
3
#include <iostream>
using namespace std;
class Area {
public:
int calc(int l, int b) { return l*b; }
};
class Perimeter {
public:
int calc(int l, int b) { return 2 * (l + b); }
};
int area_calc() {
/* Calls calc() of class Area and returns it. */
________________
}
int peri_calc() {
/* Calls calc() function of class Perimeter and returns it. */
________________
}
};
int main() {
9
int l, b;
cin >> l >> b;
return 0;
}
10
Public-1
1. Input:
4
6
Output:
24
20
2. Input:
2
3
Output:
6
10
3. Input:
65
34
Output:
2210
198
Answer
public Area, public Perimeter
Question 3
Consider the skeletal code given below. Marks: 3
Fill up the blanks by following the instructions associated with it and complete the code, so
that the output of the test cases should match. Do not change any other part of the code.
#include<iostream>
using namespace std;
class Polygon {
protected: int width, height;
public:
Polygon(int a, int b) : width(a), height(b) {}
11
public:
Rectangle(int a, int b) : Polygon(a, b) {}
int area() { return width*height; }
};
int main() {
int h, w;
cin >> h >> w;
delete ppoly1;
delete ppoly2;
return 0;
}
12
Public 1
Input:
4
5
Output: 20:10:
Public 2
Input:
30
15
Output: 450:225:
Private
Input:
8
6
Output: 48:24:
Answer
virtual int area(void) = 0; or virtual int area(void) { return 0; }
Question 4
Fill the blank by defining the proper constructor where name of the parameter should be nc
Marks 2
#include <iostream>
class Engine {
public:
Engine(int nc) :cylinder(nc){}
void start() {
cout << getCylinder() << " cylinder engine started" ;
};
int getCylinder() {
return cylinder;
}
private:
int cylinder;
};
13
class Car : private Engine
{ // Car has-a Engine
public:
//Define the constructor to run the code. Name of the parameter should be ’nc’
________________________
void start() {
cout << "car with " << Engine::getCylinder() <<
" cylinder engine started" << endl;
int main()
{
int cylin;
cin >> cylin;
Car c(cylin);
c.start();
return 0;
}
a. Input: 8
Output: car with 8 cylinder engine started
8 cylinder engine started
b. Input:10
Output: car with 10 cylinder engine started
10 cylinder engine started
c. Input:4
Output: car with 4 cylinder engine started
4 cylinder engine started
Answer
Car(int nc) : Engine(nc) { }
Engine::start();
14
Programming in C++: Assignment Week 6
Total Marks : 20
April 6, 2017
Question 1
Look at the code snippet below and find out What will be the correct syntax for up-casting ?
Mark 1
class Parent {
public:
void sleep() {}
};
int main(){
Parent parent;
Child child;
return 0;
}
Answer: c)
Explanation: By definition of upcasting (Base Class to Derive class)
Question 2
What will be the correct syntax for down-casting in above code (QS No-1)?
1
b) Child *pChild = &parent;
Answer: a)
Explanation: By definition of downcasting (Derive class to Base Class)
Question 3
Look at the following code snippet and Find out the static binding
from the option below Mark 1
class Base {
public:
void first() {}
virtual void second() {}
};
class Derived : public Base {
public:
void f() {}
virtual void g() {}
};
int main() {
Base b;
Derived d;
Base *pb = &b;
Base *pd = &d;
Base &rb = b;
Base &rd = d;
pb->first(); // 1
pd->first(); // 2
rb.first(); // 3
rd.first(); // 4
pb->second(); // 5
pd->second(); // 6
rb.second(); // 7
rd.second(); // 8
}
a) 1 2 5 6
b) 3 4 7 8
c) 1 2 3 4
d) 5 6 7 8
Answer: c)
Explanation:Direct function calls can be resolved using a process known as early binding or
static binding.
2
Question 4
Consider the code of question 3 and find out the dynamic binding from the option below
a) 1 2 5 6
b) 3 4 7 8
c) 1 2 3 4
d) 5 6 7 8
Answer: d)
Explanation: Virtual functions get resolve at run time.
Question 5
Consider the following code snippet. Find out the correct sequence of function calling. Marks:
1
class X {
public:
virtual void f() { } //1
void g() { } //2
};
class Y : public X {
public:
void f() { } //3
virtual void g() { }//4
};
int main() {
X x; Y y;
X& rx = y;
x.f();
x.g();
rx.f();
rx.g();
return 0;
}
a) 1 2 3 2
b) 1 2 3 4
c) 3 2 1 2
d) 3 2 1 4
Answer: a)
Explanation: rx.f() call Y::f as f is virtual in the base class.
3
Question 6
What will be the output/Error of the bellow code snippet?
class Base {
public:
virtual void show() = 0;
};
int main()
{
Base obj;
Base *b;
Derived d;
b = &d;
b->show();
}
d) Virtual Function
Answer: a)
Explanation: Can’t create of object of a abstract base class
Question 7
What will be the output of the following program? Marks: 1
#include<iostream>
using namespace std;
class base {
public:
base() { cout << "c"; }
virtual ~base() { cout << "~c"; }
};
int main(void)
4
{
{
derived *d = new derived();
base *b = d;
delete b;
}
return 0;
}
a) d c ∼c ∼d
b) d c ∼d ∼c
c) c d ∼c ∼d
d) c d ∼d ∼c
Answer: d)
Explanation: Deleting a derived class object using a pointer to a base class that has a non-
virtual destructor results in undefined
Question 8
Find the abstract classes from the bellow code?
class Instrument {
public:
virtual void play() = 0
{ cout << "Instrument: Init Brush" << endl; }
};
class Wind : public Instrument {
void play() { cout << "Polygon: play" << endl; }
};
class Percussion : public Instrument {
};
class Woodwind : public Wind {
public:
void play() { cout << "Woodwind: play" << endl; }
};
class Brass : public Wind {
public:
void play() { cout << "Brass: play" << endl; }
};
class Drum : public Percussion {
public:
void play() { cout << "Drum: play" << endl; }
};
class Tambourine : public Percussion {
public:
void play() { cout << "Tambourine: play" << endl; }
};
a) Woodwind, Brass
5
b) Instrument, Percussion
c) Instrument, Tambourine
d) Percussion, Drum
Answer: b)
Explanation: pure virtual function play() is there in Instrument and Percussion class
Question 9
What will be the output of the following Code Snippet ? Marks: 1
class Instrument {
public:
virtual void play()
{ cout << "1 "; }
};
class Wind : public Instrument {
void draw() { Instrument::play(); cout << "2 "; }
};
class Percussion : public Instrument {
};
class Woodwind : public Wind {
public:
void play() { Instrument::play(); cout << "3 "; }
};
class Brass : public Wind {
public:
void play() { Instrument::play(); cout << "4 "; }
};
class Drum : public Percussion {
public:
void play() { Instrument::play(); cout << "5 "; }
};
class Tambourine : public Percussion {
public:
void play() { Instrument::play(); cout << "6 "; }
};
int main() {
Instrument *arr[] = { new Woodwind, new Brass, new Drum, new Tambourine };
for (int i = 0; i < sizeof(arr) / sizeof(Instrument *); ++i) arr[i]->play();
return 0;
}
a) 3 4 5 6
b) 1 3 1 4 1 5 1 6
c) 1 3 4 5 6
d) Compile Time Error: Virtual function can’t have body
Answer: b)
Explanation:: Virtual function may have body
6
Question 10
What will be the output of the following code snippet? Marks: 1
A a;
B b;
a.i = 8;
b.d = 9.7;
A *p = &a;
B *q = &b;
p = (A*)&b;
q = (B*)&a;
cout << p->i << endl;
cout << q->d << endl;
a) 9.7 8
b) 8 9.7
c) GARBAGE
Answer: c)
Programming Questions
Question 1
Problem Statement: Marks: 2
Consider the following code. Modify the code in editable section to match the public test cases.
#include <iostream>
using namespace std;
class B {
public:
B() { cout << "98 "; } // don’t modify the "cout"
};
class D : public B {
7
int n;
public:
D(int p):n(p) { cout << n << " "; }
~D() { cout << n*2 << " "; }
};
int main() {
int n ; cin >> n ;
delete basePtr;
return 0;
}
//---------------------------------------------------------------------
Public-1
Input:
2
Output:
98 2 4 56
Public-2
Input:
8
Output:
98 8 16 56
Private
Input:
3
Output:
98 3 6 56
Answer: virtual
Question 2
Consider the skeletal code below. When the program is executed, the member functions
(excluding the constructors and destructors) are called in the order: A::g B::g B::f A::g
B::g C::g C::f. Fill up the blanks to match the test cases. Marks: 2
#include <iostream>
using namespace std;
8
};
class B : public A { protected: int bi;
public:
B(int i) : A(i), bi(i) {}
_______ void f() // Fill the blank or Remove blank
{ cout << ai << bi; } // DO NOT EDIT THIS LINE
Public 1
Input: 2
Output: 43322
Public 2
Input: 23
Output: 43242323
Private
Input: 4
Output: 43544
Question 3
Consider the following code. write the proper definition of ”getArea()” in the editable section
so that the test cases would pass . Marks: 2
9
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Rect.setWidth(x);
Rect.setHeight(y);
Tri.setWidth(x);
Tri.setHeight(y);
while (*pShape)
cout << (*pShape++)->getArea() << " ";
return 0;
}
10
Public-1
Input:
3
7
Output:
21 10
Public-2
Input:
35
23
Output:
805 402
Private
Input:
6
9
Output:
54 27
Answer:
Question 4
Consider the following code. Fill up the code in editable section to congratulate the Manager
and the Clerk, so that outputs will be matched as given in the test cases. Marks: 2
#include <iostream>
#include <string>
using namespace std;
class Employee {
public:
string Name;
double salary;
Employee(string fName, double sal) : Name(fName), salary(sal) {}
void show() {
cout << Name << " " << salary;
}
void addBonus(double bonus) {
salary += bonus;
}
};
class Manager :public Employee {
public:
Manager(string fName, double sal) : Employee(fName, sal) {}
};
11
class Clerk :public Employee {
public:
Clerk(string fName, double sal) : Employee(fName, sal) {}
};
// Call the proper function to congratulate the Manager and the Clerk
return 0;
}
Public-1
Input:
2000
1000
Output:
Kevin 2200 Steve 1200
Public-2
Input:
4000
1000
Output:
Kevin 4200 Steve 1200
Private
Input:
6200
2500
Output:
Kevin 6400 Steve 2700
Answer:
congratulate(&c1);
congratulate(&m1);
12
Question 5
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
Shape(int a = 0, int b = 0) {
width = a;
height = b;
}
// Fill the blank to run the code
__________ void area() {
cout << "Parent class area :" << endl;
}
};
13
shape->area();
return 0;
}
Public-1
Input:
10 5
Output:
50 25
Public-2
Input:
10 25
Output:
250 125
Private
Input:
60 30
Output:
1800 900
Answer:
virtual
shape = &rec;
shape = &tri;
14
Programming in C++: Assignment Week 7
Total Marks : 20
April 5, 2017
Question 1
Find out the output of the following program? Marks: 1
#include <iostream>
using namespace std;
int main(void){
const int val = 10;
const int *ptr = &val;
int *ptr1 = const_cast <int *>(ptr);
*ptr1 = fun(ptr1);
fun(*ptr1);
cout << *ptr;
return 0;
}
a) 10
b) 100
c) 20
d) Compilation error
Answer: b)
Solution: Function fun() expects a pointer to an int, not a const int. The statement
int *ptr1 = const_cast <int *>(ptr)}
returns a pointer ptr1 that refers to a without the const qualification of val.
1
Question 2
What will be the output of the following program? Marks: 1
#include<iostream>
using namespace std;
class Person {
public:
Person(int x) { cout << 2 * x << " "; }
Person() { cout << 3 << " "; }
};
int main() {
TA ta1(30);
}
a) 90 90 150
b) 150 90 90
c) 3 90 90 150
d) 60 90 90 150
Answer: c)
Solution: constructor and Destructor of Person will also be called two times when object ta1
is constructed and destructed. So object ta1 has two copies of all members of Person, this
causes ambiguities. The solution to this problem is virtual keyword. We make the classes
Faculty and Student as virtual base classes to avoid two copies of Person in TA class.
Question 3
How many virtual table will be set up by the compiler for the following code ? Marks: 1
2
class Base {
public:
virtual void function1() {};
virtual void function2() {};
};
a) 0
b) 1
c) 2
d) 3
Answer: d)
Solution: Because there are 3 classes here, the compiler will set up 3 virtual tables: one for
Base, one for D1, and one for D2.
Question 4
For the above code (Question 3) what will be the virtual function table entry for function1 &
function2 in class D2? Marks: 1
c) D1::function1()only
Answer: a)
Solution: VFT for Class base– Base::fucntion1() & Base::function2()
VFT for Class D1– D1::fucntion1() & Base::function2()
VFT for Class D2– Base::fucntion1() & D2::function2()
Question 5
In the above code(Ref:Question 3), in which classes the compiler automatically add a hidden
pointer to the virtual function table?
a) Base, D1, D2
3
b) Base only
c) D1, D2
d) Base, D1
Answer: a)
Solution: Whenever a class defines a virtual function a hidden member variable is added to
the class which points to an array of pointers to (virtual) functions called the Virtual Function
Table (VFT)
Question 6
Look at the code given below. Identify the statements where correct use of staic cast operator
has been done. MCQ, Mark 1
#include <iostream>
using namespace std;
int main(){
float f = 12.3;
float* pf = &f;
return 0;
}
a) stmt-1, stmt-2
b) stmt-2, stmt-3
c) stmt-1, stmt-3
Answer: c)
Solution: In stmt-2, types pointed to are unrelated.
Question 7
Fill the blank by an appropriate cast operator given that the output of the program is:Failure
SA, Marks: 1
#include <iostream>
using namespace std;
int main() {
4
// Fill the blank by appropriate caste operator
Derived *pd = ___________ <Derived*>(new Base);
return 0;
}
Question 8
Look at the following code snippet. If typeid(*ap).name() and typeid(ar).name() will be called,
then it will refer to which structure/s. Marks: 1
#include <iostream>
#include <typeinfo>
using namespace std;
int main() {
B obj;
A* ap = &obj;
A& ar = obj;
return 0;
}
a) struct A struct B
b) struct A struct A
c) struct B struct B
d) struct B struct A
Answer: c)
Solution: If the expression points to a base class type, yet the object is actually of a type
derived from that base class, a type info reference for the derived class is the result.
Question 9
Consider the following code snippet. What will be output of the code below? Marks: 1
class Base {
protected:
int marker;
public:
Base(int m = 4) : marker(m) {}
5
virtual ~Base() {};
virtual void Action() { ++marker; }
};
class Derived : public Base {
public:
void Action() {
static_cast<Base>(*this).Action();
marker *= 2;
cout << marker << endl;
}
};
int main() {
Base *p = new Derived;
p->Action();
return 0;
}
a) 8
b) 10
c) 4
d) 32
Answer: a)
Solution: static cast<Base>(*this).Action() explicitly call a single-argument construc-
tor. Hence, value of marker is becoming 4 again after the
static cast<Base>(*this).Action() call.
Question 10
static cast can be used for
1. Downcast
2. Upcast
3. Implicit conversions
4. User-defined conversions
a) 1 2 3
b) 1 3 4
c) 3 4 2
d) 1 2 3 4
Answer: d)
Solution: By the definition of static cast
6
Programming Questions
Question 1
Fill the bank with appropriate casting Marks: 3
#include <iostream>
using namespace std;
class Base {
public:
virtual void DoIt() = 0; // pure virtual
virtual ~Base() {};
};
Base* CreateRandom(int x) {
if ((x % 2) == 0)
return new Foo;
else
return new Bar;
}
int main() {
int lim = 0;
cin >> lim;
for (int n = 0; n < lim; ++n) {
7
Public 1
Input: 1
Output: 12,13,
Public 2
Input: 2
Output: 12,13,14,15:
Public 3
Input: 3
Output: 12,13,14,15:12,13,
Private
Input: 4
Output: 12,13,14,15:12,13,14,15:
Answer:
Solution: The casts execute at runtime, and work by querying the object (no need to worry
about how for now), asking it if it the type we’re looking for. If it is, dynamic cast<Type*>
returns a pointer; otherwise it returns NULL.
Question 2
Problem statement: Consider the following program. Fill the blank With proper constructor
/ conversion operator for the given casting to match the outputs of test cases. Marks: 2
#include <iostream>
using namespace std;
class A {
int i;
public:
A(int ai) : i(ai) {}
int get() const { return i; }
void update() { ++i; }
};
class B {
int i;
public:
B(int ai) : i(ai) {}
int get() const { return i; }
8
_____________________________
//-------------------------- Suffix Fixed Code --------------------------
void update() { ++i; }
};
int main() {
int i;
cin >> i;
A a(i++);
B b(i);
B &r = static_cast<B>(a);
a.update();
cout << a.get() << ":";
cout << r.get() << ":";
A &s = static_cast<A>(b);
b.update();
cout << b.get() << ":";
cout << s.get() << ":";
return 0;
}
//------------------------------------------------------------------
Public 1
Input:
1
Output: 2:1:3:2:
Public 2
Input:
15
Output: 16:15:17:16:
Private
Input:
5
Output: 6:5:7:6:
Answer:
B(A& a) : i(a.get()) {}
Question 3
Problem Statement: Write the appropriate constructor / operator function in the following
program to cast a class A object to a char * object. Marks: 2
9
//------------------------- Prefixed Fixed Code --------------------------
#include <iostream>
#include <cstring>
using namespace std;
class A {
public: char *str;
____________________________________
int main() {
char input[20];
cin >> input;
A a(input);
// A ==> char *
char *s = static_cast<char*>(a);
strcat(s, "-success");
cout << s;
return 0;
}
//--------------------------------------------------------------------
Public 1
Input: string
Output: string-success
Public 2
Input: what
Output: what-success
Private
Input: My
Output: My-success
Answer:
10
Question 4
Consider the following code snippet and fill the bank with appropriate code. Marks: 3
#include <iostream>
using namespace std;
class student {
private:
int roll;
public:
student(int r) :roll(r) {}
int main(void) {
int old_roll_no = 0;
cin >> old_roll_no;
student s(old_roll_no);
cout << s.getRoll() << " ";
s.fun();
cout << s.getRoll() ;
return 0;
}
Public 1
Input: 3
Output: 3 5
Public 2
Input: 12
Output: 12 5
Private
Input: 1
Output: 1 5
Answer:
(const_cast <student*>(this))->roll = 5;
Solution: const cast can be used to change non-const class members inside a const member
function.
11
Programming in C++: Assignment Week 8
Total Marks : 20
Question 1
What will be the output of the following program? Marks: 1
int main()
{
try {
throw ’a’;
}
catch (int x) {
cout << "Caught 1 " << x;
}
catch (double x) {
cout << "Caught 2 " << x;
}
catch (string x) {
cout << "Caught 3 " << x;
}
catch (...) {
cout << "Default Exception";
}
return 0;
}
a) Caught 1 a
b) Caught 2 a
c) Caught 3 a
d) Default Exception
Answer: d)
Solution: No catch argument type matches the type of the thrown object. If the ellipsis
(...) is used as the parameter of catch, then that handler can catch any exception no matter
what the type of the exception thrown. This can be used as a default handler that catches all
exceptions not caught by other handlers.
1
Question 2
Consider the following code snippet and find appropriate option to fill the blank. Marks: 2
_________________ {
T result;
result = (a>b)? a : b;
return (result);
}
int main () {
int i = 5, j = 6, k;
long l = 10, m = 5, n;
k = GetMax<int>(i,j);
n = GetMax<long>(l,m);
d) class GetMax
Answer: b)
Solution: By the definition of template
Question 3
What will be the output of the following code snippet? Marks: 1
int main() {
2
myFunction(1);
myFunction(2);
myFunction(0);
myFunction(3);
return 0;
}
Answer: d)
Solution: Multiple handlers (i.e., catch expressions) can be chained; each one with a different
parameter type. Only the handler whose argument type matches the type of the exception
specified in the throw statement is executed.
Question 4
What will be the output of the following code snippet? Marks: 1
#include<iostream>
using namespace std;
struct MyException : public exception {
const char * what () const throw () {
return "C++ Exception";
}
};
int main() {
try {
throw MyException();
}catch(MyException& e) {
std::cout << "MyException caught" << std::endl;
std::cout << e.what() << std::endl;
} catch(std::exception& e) {
std::cout << "Exception caught" << std::endl;
std::cout << e.what() << std::endl;
}
}
a) MyException caught
C++ Exception
b) C++ Exception
MyException caught
c) Exception caught
C++ Exception
3
d) C++ Exception
MyException caught
Exception caught
Answer: a)
Solution: Multiple handlers (i.e., catch expressions) can be chained; each one with a different
parameter type. Only the handler whose argument type matches the type of the exception
specified in the throw statement is executed.
Question 5
What will the the output of the following code? Marks: 1
#include <iostream>
using namespace std;
class X {
public:
class Trouble {};
class Small : public Trouble {};
class Big : public Trouble {};
void f() { throw Big(); }
};
int main() {
X x;
try {
x.f();
}
catch (X::Trouble&) {
cout << "caught Trouble" << endl;
}
catch (X::Small&) {
cout << "caught Small Trouble" << endl;
}
catch (X::Big&) {
cout << "caught Big Trouble" << endl;
}
catch (...) {
cout << "default" << endl;
}
return 0;
}
a) caught Trouble
d) default
Answer: a)
4
Solution: Multiple handlers (i.e., catch expressions) can be chained; each one with a different
parameter type. Only the handler whose argument type matches the type of the exception
specified in the throw statement is executed.
Question 6
What will be the output of the following program? MCQ, Marks 2
#include <iostream>
using namespace std;
class Test {
public:
Test() { cout << "In Constructor" << endl; }
~Test() { cout << "In Destructor " << endl; }
};
int main() {
try {
Test t1;
throw 10.00;
}
catch(int i) {
cout << "Caught Integer " << i << endl;
}
catch(...) {
cout << "Caught Default" << endl;
}
return 0;
}
a) In Constructor
In destructor
Caught Integer 10
Caught Default
b) In Constructor
Caught Integer 10
c) In Constructor
In Destructor
Caught Default
d) In Constructor
Caught Default
Answer: c)
Solution: Multiple handlers (i.e., catch expressions) can be chained; each one with a different
parameter type. Only the handler whose argument type matches the type of the exception
specified in the throw statement is executed.
5
Question 7
Fill in the blank in the following code to get the desired output. MCQ, Marks 2
#include <iostream>
using namespace std;
return m;
}
int main() {
int arr1[] = {10, 20, 15, 12};
int n1 = sizeof(arr1)/sizeof(arr1[0]);
return 0;
}
------------
Output:
10
1
Answer: d)
Solution: By the definition of template
6
Programming Questions
Question 1
Consider the following code. Modify the code in editable section to match the public test cases.
Marks: 3
#include<iostream>
#include<string>
using namespace std;
int main() {
int a, b;
double s, t;
string mr, ms;
cin >> a >> b >> s >> t ;
cin >> mr >> ms ;
Swap(a, b);
Swap(s, t);
swap(mr, ms);
Public 1
I/P: 20 30 2.3 5.6 ppd tm
O/P: 30 20 5.6 2.3 tm ppd
Public 2
I/P: 45 34 7.9 5.6 kolkata delhi
O/P: 34 45 5.6 7.9 delhi kolkata
Private
I/P: 15 78 4.76 2.45 sm ppm
O/P: 78 15 2.45 4.76 ppm sm
Answer
template<typename T>
void Swap(T& x, T& y)
{
T tmp = x;
x = y;
y = tmp;
}
7
Question 2
Consider the following code.Define the proper function in editable section. Marks: 2
#include <iostream>
#include <exception>
using namespace std;
} myex;
class DivideByZero {
public:
int numerator, denominator;
DivideByZero(int a = 0, int b = 0) : numerator(a), denominator(b){}
int divide(int numerator, int denominator){
if (denominator == 0) {
throw myex;
}
return numerator / denominator;
}
};
int main() {
DivideByZero d;
int a, b;
cin >> a >> b;
try
{
d.divide(a, b);
}
catch (exception& e)
{
cout << e.what() << ’\n’;
}
return 0;
}
Public-1
Input: 10 0
Output: DivideByZero
Public-2
Input: 12 0
Output: DivideByZero
8
Private
Input: 8 0
Output: DivideByZero
9
Answer
Question 3
Consider the following code. Fill the blank with proper class header Marks: 2
#include<iostream>
using namespace std;
// Write the class header here
_______________________
class A {
public:
T x;
U y;
A() { cout << "called" << endl; }
A(T x, U y){ cout << x << ’ ’ << y << endl; };
};
int main() {
int num1 = 0;
double num2 = 0;
char c;
cin >> num1;
cin >> num2;
cin >> c;
A<char> a;
A<char, int> (c, num1);
A<int, double> (num1, num2);
return 0;
}
Public-1
Input:
2
3.4
n
Output:
called
n 2
2 3.4
Public-2
Input:
5
5.4
i
10
Output:
called
i 5
5 5.4
Private
Input:
3
3.4
p
Output:
called
p 3
3 3.4
Answer
template<class T, class U = int >
class A {
public:
T x;
U y;
A() { cout << "called" << endl; }
A(T x, U y){ cout << x << ’ ’ << y << endl; };
};
Question 4
Consider the following code. Modify the code in editable section to match the public test cases.
Marks: 3
#include <iostream>
#include <vector>
using namespace std;
class Test {
static int count;
int id;
public:
Test(int id) {
count++;
cout << count << ’ ’;
if (count == id)
throw id;
}
~Test() {}
};
int Test::count = 0;
int main() {
int n, m = 0;
cin >> n >> m;
11
_______________________ // Declare testArray here
try {
for (int i = 0; i < n; ++i) {
testArray.push_back(Test(m));
}
}
_______________________// Write the catch here
{
cout << "Caught " << i << endl;
}
return 0;
}
Public-1
Input:
6
5
Output:
1 2 3 4 5 Caught 5
Public-2
Input:
8
6
Output:
1 2 3 4 5 6 Caught 6
Private
Input:
3
3
Output:
1 2 3 Caught 3
Answer
catch (int i)
vector<Test> testArray;
12
Programming in C++: Assignment Week 4
Total Marks : 20
Question 1
Using friend operator function, which set of operators can be overloaded? Mark 1
b. + , - , / , *
c. = , ( ) , [ ] , ->
d. && , = , * , ->
Answer: a
Explanation: As per language syntax, check slides
Question 2
While overloading I/O stream how many number of parameters are required in operator func-
tion ? Mark 1
a. 0
b. 1
c. 2
d. 3
Answer: c
Explanation: Check slides
Question 3
What is the output of the following code? Mark 1
#include <iostream>
using namespace std;
struct emp {
int a;
emp ( int b): a(b){}
~emp(){ cout << " Destroyed " ;}
void disp(){ cout << " In Display " ; }
};
int main(){
1
emp e(20);
cout << e.a ;
e.disp();
}
a. Compilation error
b. 20 In Display
c. 20 In Display Destroyed
d. 0 In Display
Answer: c
Explanation: As per execution semantics of classes and objects, check slides
Question 4
What is the output of the following code? Mark 1
#include <iostream>
using namespace std ;
namespace Ex { int x = 10; }
namespace Ex { int y = 10; }
int main(){
using namespace Ex ;
x = y = 50;
cout << x << " " << y;
}
a. 10 10
b. 50 50
Question 5
Fill in the blank. Mark 1
#include<iostream>
using namespace std;
class Test { static int x;
public:
void get() { x = 15; }
void print() {
x = x + 20;
cout << "x =" << x << endl;
2
}
};
____________; // Define static variable ’x’
int main() {
Test o1, o2;
o1.get(); o2.get();
o1.print(); o2.print();
return 0;
}
b) Test t; t.x = 0;
c) int Test::x = 0;
d) Test t; t::x = 0;
Answer: c)
Explanation: Static variables are declared and initialised with class name, check slides
Question 6
What will be the output of the following program? Mark 1
#include<iostream>
using namespace std;
class Test { int x;
public:
Test(int i) : x(i) {}
friend void print(const Test& a);
};
void print(const Test& a) {
cout << "x = " << a.x;
}
int main(){
Test t(10);
print(t);
return 0;
}
a) x = 10
Answer: a)
Explanation: X can be accessed as print is a friend function
3
Question 7
What will be the output of the following program? Mark 1
#include <iostream>
using namespace std;
class sample {
public:
int x, y;
sample() {};
sample(int, int);
sample operator + (sample);
};
sample::sample (int a, int b) {
x = a;
y = b;
}
sample sample::operator+ (sample param) {
sample temp;
temp.x = x + param.x;
temp.y = y + param.y;
return (temp);
}
int main () {
sample a (4,1);
sample b (3,2);
sample c;
c = a + b;
cout << c.x << " " << c.y;
return 0;
}
a) 5 5
b) 7 3
c) 3 7
d) 4 6
Answer: b)
Explanation: using operator overloading of + with class Sample objects
Question 8
What will be the output of the following program? Mark 1
#include <iostream>
using namespace std;
class Test {
4
int i;
public:
Test(int ii) : i(ii) {}
const Test operator+(const Test& rv) const {
cout << "Executes +" << endl;
return Test(i + rv.i);
}
Test& operator+=(const Test& rv) {
cout << "Executes +=" << endl;
i += rv.i;
return *this;
}
};
int main() {
int i = 1, j = 2, k = 3;
k += i + j;
Test ii(1), jj(2), kk(3);
kk += ii + jj;
}
a) Executes +
Executes +=
b) Executes +
Executes +
c) Executes +=
Executes +
Answer: a)
Explanation: As per precedence
Question 9
Fill in the blanks Mark 1
#include <iostream>
using namespace std;
class Complex { double re, im; public:
explicit Complex(double r = 0, double i = 0) : re(r), im(i) { }
void disp() { cout << re << " +j " << im << endl; }
friend Complex operator+ (const Complex &a, const Complex &b) {
return Complex(a.re + b.re, a.im + b.im);
}
friend Complex operator+ (const Complex &a, double d) {
Complex b(d); return a + b;
}
__________________________________________________ {
Complex a(d); return a + b;
5
}
};
int main(){
Complex d1(2.5, 3.2), d2(1.6, 3.3), d3;
d3 = d1 + d2; d3.disp();
d3 = d1 + 6.2; d3.disp();
d3 = 4.2 + d2; d3.disp();
return 0;
}
Answer: d)
Explanation: As Complex a(d) is created in the body, hence option d
Question 10
Identify the Incorrect statement(s) about static data member of a class. Mark 1
a) It needs to be defined to avoid linker error.
Programming Assignment
Question 1
Write down the required keywords in the first blank. Fill the rest of the blank by calling
the user defined function abs() or library function abs(), So that the given test cases will be
satisfied Marks 2
#include <iostream>
#include <cstdlib>
____________ NS { // Fill the blank with proper keyword
int abs(int n) {
if (n < -128) return 0;
if (n > 127) return 0;
if (n < 0) return -n;
return n;
}
}
int main() {
6
double x, y, z;
std::cin >> x >> y >> z ;
std::cout << _______(x) << " "
<< _______(y) << " "
<< _______(z) << std::endl;
std::cout <<_______(x) << " "
<< _______(y) << " "
<< _______(z) << std::endl;
return 0;
}
Output: 0 69 9
203 69 9
Output: 0 45 0
178 45 0
Output: 114 20 2
114 20 2
Question 2
Here S and R Represent two geometric class, Square and Rectangle respectively. Our objective
is to convert /Interpret the Square object as Rectangle and calculating the area of rectangle.
Marks 2
#include <iostream>
using namespace std;
class S;
class R {
int width, height;
public:
int area () // Area of rectangle
{return (width * height);}
void convert (S a);
};
class S {
7
_____________________; // Fill the blank
private:
int side;
public:
S (int a) : side(a) {}
};
void ____________________ (S a) {
width = a.side;
height = a.side; // Interpreting Square as an rectangle
}
int main () {
int x;
cin >> x;
R rect;
S sqr (x);
rect.convert(sqr);
cout << rect.area();
return 0;
}
a. Input: 4
Output: 16
b. Input: -6
Output: 36
c. Input: -2.5
Output: 4
Question 3
This Program is all about the implementation of Pre/Post Incrementer. Fill the blank By
keeping this in mind so that the given test cases will satisfy. Marks 2
#include <iostream>
using namespace std;
8
class MyClass { int data;
public:
_____________________{ } // Define Constructor
MyClass& operator++() {
++data;
return ___________;
}
_____________________________ {
MyClass t(data);
++data;
return ______________;
}
void disp() { cout << " " << data ; }
};
int main() {
int x;
cin >> x;
MyClass obj1(x);
obj1.disp();
MyClass obj2 = obj1++;
obj2.disp();
obj2 = ++obj1;
obj2.disp();
return 0;
}
a. Input: 4
Output: 4 4 6
b. Input: -9
Output: -9 -9 -7
c. Input: 0
Output: 0 0 2
Question 4
Here display() is a non member function which should display the data member of Myclass.
Apply the proper concept to fill the blank so that the given test cases will pass. Marks 2
9
#include<iostream>
using namespace std;
class MyClass { int x_;
public:
MyClass(int i) : x_(i) {}
________________________; // Declare the display function.
};
void display(__________________) {
cout << " " << a.x_;
}
int main(){
int x;
cin >> x;
MyClass obj(x);
display(obj);
return 0;
}
a. Input: 4
Output: 4
b. Input: 8.7
Output: 8
c. Input: 0
Output: 0
Question 5
Fill the blank by keeping in mind that, the program tests the conceptual knowledge about
staticMarks 2
#include<iostream>
using namespace std;
class MyClass { static int x;
public:
10
void get() { x++; }
_______ ________ print(int y) { //Fill the blank with proper key words
x = x - y;
cout << " " << x ;
}
};
______________________; // Define static data member
int main() {
int x;
cin >> x;
MyClass:: print(x);
MyClass o1;
o1.get();
o1.print(x);
return 0;
}
a. Input: 5
Output: -4 -8
b. Input: 0
Output: 1 2
c. Input: -7
Output: 8 16
11