Programming in C++: Assignment Week 1 Total Marks : 20 Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology Kharagpur – 721302 [email protected]February 24, 2017 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
91
Embed
Programming in C++: Assignment Week 1 - WordPress.com · Programming in C++: Assignment Week 1 Total Marks : 20 ... What will be the output of the following program? Marks 2 #include
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Programming in C++: Assignment Week 1
Total Marks : 20
Partha Pratim DasDepartment of Computer Science and Engineering
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
void sum(int x, int y) {
x++; y++;
return (y);
}
a) The incremented value of y
b) The incremented value of y; the value of x is incremented but not returned
c) Compilation Error: return value type does not match the function type
d) Does not incremented value of y
Answer: c)Explanation: The return type of the function is void, hence an integer value cannot bereturned.
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 equivalentASCII
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
c) Will always output 1
d) 34 1
Answer: d)Explanation: The base pointer of the array is used to point to an integer 34. In main, thearray 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;
}
a) divide by zero error
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));
}
a) Compilation Error: Error in function call
b) 7
c) 4.5
d) 5.5
Answer: b)Explanation: function pointer is a pointer defined for any function with 3 integer parametersand 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";
string str3 = _______________________;
cout << str3;
return 0;
}
Output: I Travel
a) str1+str2
b) strcat(str1,str2);
c) strcat(strcpy(str3,str1),str2);
d) str1.append(str2)
Answer: a) str1+str2 and d) str1.append(str2)Explanation: str1 and str 2 are two string type variables, operations possible for concate-nation are str1+str2 (String is a stl, hence has + operator overloaded) and str1.append(str2)to append strings.
4
Question 10
What will be the output of the following program? Marks 2
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 printedat 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;
}
a) A#: vector <int> arr(count);B#: arr.resize(count);
b) A#: vector <int> arr(count);B#: arr.size(count);
c) A#: vector <int> arr;B#: arr.size(count);
d) A#: vector <int> arr;B#: arr.resize(count);
Answer: d)Explanation: As per syntax, using resize operator
6
Programming in C++: Assignment Week 2Total Marks : 20
Each question carries one markRight hand side of each question shows its Type (MCQ/MSQ)
March 3, 2017
Question 1
• Look at the code snippet below:
int * const p = &n;
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-PointeeAnswer: aExplanation: As per syntax, refer slides
Question 2
• Look at the following code segment and decide which statement(s) is/are correct. Mark1
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-5Answer: c, dExplanation: 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() {
typedef struct Complex {
double re;
double im;
} Complex;
const Complex c = {2,4} ;
c.re = 5.9;
cout << c.re;
return 0;
}
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.reAnswer: dExplanation: 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;
}
a. TWO and PI are variables
b. Types of TWO and PI may be indeterminate
c. Types of TWO and PI are determinate
2
d. TWO and PI look like variablesAnswer: 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;
}
a. Cannot return constant parameter
b. Cannot edit constant parameter
c. 8 26
d. 8 25.12Answer: d)Explanation: Const used to pass reference parameter param to prevent frombeing modified. The value of param is used only
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 funcAnswer: d)Explanation: Default values needs to specified from the end, hence functionresoultion 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);
cout << " " << u << endl;
return 0;
}
a. Add cannot be overloaded with different return types
b. Add cannot be resolved
c. 3 5.5
d. 3 6.5Answer: c)Explanation: Two versions of function Add called as per resolution
Question 8
• Which function prototype will match the function call func(3.6,7)? Mark 1
void func(int, int); // Proto 1
void func(double, double, double = 5.6); // Proto 2
d. Proto 4Answer: 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 mismatchin 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;
}
a. ptr cannot point to NULL
b. delete ptr (NULL) causes program crash
c. Output: In Program
d. Invalid SyntaxAnswer: c)Explanation: Null assignment to pointer allowed. Normal print provides theoutput
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;
cout << s3.str << endl;
return 0;
}
a. String + operator(const String& s1, const String& 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 thefunction Ref func() to get the desired output according to the test cases. Marks 2
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
c) Cannot be determined before memory allocation
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;
}
};
a) Only setx() and sety()
b) Only print()
c) setx(), sety(), calc1(), calc2()
d) setx(), sety(), calc1()
Answer: d)Explanation: The state of a class is the collection of values of all the member variables of aclass at a point. setx(), calc1() and sety() modifies the values of the member variables of theclass. 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
PROGRAM 1 // Implementation of class Test
#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;
}
};
int main() { // Application section
Test t;
t.setx(5);
}
Now if we make some changes to the class as given below.
PROGRAM 2 // Updated Implementation of class Test
#include<iostream>
using namespace std;
class Test {
int x_[2];
int y_;
public:
void print() { cout << x_[0] << " " << y_; }
void setx(int m_) { x_[0] = m_; x_[1] = 0; }
void sety(int n_) { y_ = n_; }
int calc1(int n_) {
int t;
t = n_ * x_[0] * y_;
x_[0] = n_ * 3;
return t;
}
void calc2(int n_) {
int t;
4
t = n_ * x_[0];
cout << t;
}
};
What changes would be required in the application section?
a) Create different objects
b) No change required
c) Pass different parameters to the setx() and sety() function
d) Pass different parameters to the calc1() and calc2() function
Answer: b)Explanation: The implementation of the private members of the class is changed, but itdid 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
a) Test(const Test t), Test(Test t);
b) Test(const Test* t), Test(Test* t);
c) Test(Test& t), Test(Test* t);
d) Test(const Test& t), Test(Test& t);
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
d) Compilation Error: Variable x is private in Sample, cannot be accessed in class Experiment
Answer: d)Explanation: Private data members of a class cannot be accessed by other classes or globalfunctions.
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;
}
a) s1 Created s2 Created s2 Destroyed s1 Destroyed
b) s1 Created s2 Created s1 Destroyed s2 Destroyed
c) s2 Created s1 Created s2 Destroyed s1 Destroyed
d) s1 Created s2 Created
Answer: d)Explanation: s1 and s2 created by new operator, delete operator should be used to call thedestructor, as in this case the destructor is not called implicitly.
a) Compilation Error: print attr dob() cannot assign value to dob
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. Constantdata 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 perthe 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;
cin >> x >> y >> z;
Complex n1(x,y);
cout << *n1.re << "+" << *n1.im << "i ";
Complex n2 = n1;
cout << *n2.re << "+" << *n2.im << "i ";
*n1.im = z;
cout << *n2.re << "+" << *n2.im << "i ";
cout << *n1.re << "+" << *n1.im << "i ";
return 0;
}
Answer: double r, double m // const Complex &tExplanation: The first parameters are for the constructor, the second arguments are forthe copy constructor which passes a constant Complex object, so that the value of the datamembers are not changed.
a. Input: 4, 5, 6 Output: 4+5i 4+5i 4+5i 4+6i
b. Input: 4, 5, 5 Output: 4+5i 4+5i 4+5i 4+5i
c. Input: 6 7 8 Output: 6+7i 6+7i 6+7i 6+8i
9
Question 2
Write the required syntax for the constructor to get the output as per the test cases. Marks 2
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 ofthe 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 asper 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];
cin >> str;
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
a. Input: ABCDE ; Output: DCBA
b. Input: MADAM ; Output: ADAM
c. Input: APA ; Output: PA
Question 4
Look into the main() function write the proper constructor by filling the blank to get theoutput as per the test cases. Marks 2
Answer: double re = 0.0, double im = 0.0Explanation: The default value of the double parameters of the constructor Complex willbe 0.0,0.0 as it is evaluated so in case of Complex e call
a. Input: 4.5, 5.5 ;
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 wordto 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;
}
Answer: mutable // const // constExplanation: A mutable data member x only can be accessed and updated in a constmember function.
a. Input: 4, 5, 6 ; Output: 6
b. Input: 1, 1, 0 ; Output: 0
c. Input: 70, 89, 70 ; Output: 70
13
Programming in C++: Assignment Week 5
Total Marks : 20
Partha Pratim DasDepartment of Computer Science and Engineering
Look at the code snippet bellow. Find out the sequence in which the function area() associatedwith 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;}
};
class Rectangle: public Polygon {
public:
int area ()
{ /* Function definition */ } // Area-1
};
class Triangle: public Polygon {
public:
int area ()
{ /* Function definition */ } // Area-2
};
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;
class Base { public:
int var_;
void func(int){}
};
class Derived: public Base { public:
int varD_;
void func(int){}
};
int main() {
Derived d;
d.func(1);
return 0;
}
a) Base::func(int)
b) Derived::func(int)
c) Compilation Error
d) Base::func(int) then Derived::func(int)
Answer: b) Solution: d is a Derived class object
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
b) Compilation Error: Can’t access Dog::tail
c) Compilation Error: Can’t access Animal::legs
d) 4 1
Answer: d) Solution: legs is inherited from the Animal class
Question 4
Look at the code snippet bellow. Find out, which of the show() function will be called bycalling 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;
}
a) show() of Base class only
b) show() of Derived Class only
c) Both but, show() of Derived Class first then Base class
d) Both but, show() of Base class first then Derived Class
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 bycalling 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;
}
a) show() of Base class only
b) show() of Derived Class only
c) Both but, show() of Derived Class first then Base class
d) Both but, show() of Base class first then Derived Class
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
Answer: b) Solution: In Inheritance, destructors are executed in reverse order of constructorexecution
Question 7
Identify the correct statements? Mark 1
class base {
public:
int x;
protected:
int y;
private:
int z;
};
class publicDerived: public base
{
//1. x is public
//2. y is protected
//3. z is accessible from publicDerived
};
class protectedDerived: protected base
{
//4. x is public
//5. y is protected
//6. z is not accessible from protectedDerived
};
class privateDerived: private base
{
//7. x is private
//8. y is protected
//9. z is not accessible from privateDerived
}
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
#include <iostream> // ---1
using namespace std; // ---2
class Base { protected: // ---3
int var_; // ---4
public: // ---5
Base():var_(0){} // ---6
}; // ---7
class Derived: public Base { public: // ---8
int varD_; // ---9
void print () { cout << var_; } // ---10
}; // ---11
int main() { // ---12
Derived d; // ---13
d.var_ = 1; // ---14
d.varD_ = 1; // ---15
cout << d.var_ <<" " << d.varD_; // ---16
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;
}
a) Return an integer value
b) Compiler Error: cannot declare variable ’t’ to be of abstract
c) Compiler Error: cannot access private variable x
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;
Shape(int a = 0, int b = 0): x(a), y(b) {}
void draw()
{ cout << x << " " << y << " "; }
};
class Rectangle : public Shape {
public:
int w, h;
Rectangle(int a = 5, int b = 6): w(a), h(b), Shape(7, 8) {}
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 and2.
Programming Questions
Question 1
Consider the skeletal code given below and Fill the blank or remove the blank in the headerof 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; }
________ float calculateArea(){
return l*l;
}
};
class Circle : public Shape {
public:
_________ float calculateArea(){
return 3.14*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: 5Output: 78.5
b. Input: 28Output: 2461.76
c. Input: 45Output: 6358.5
Answer: virtualSolution: Derived class function is called using a base class pointer. virtual function is resolvedlate, at runtime.
Question 2
Consider the skeletal code given below.Fill up the blank by following the instructions associatedwith 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); }
};
/* Rectangle class is derived from classes Area and Perimeter. */
class Rectangle: ________________ { // Inherit the required base classes
private:
int length, breadth;
public:
Rectangle(int l, int b) : length(l), breadth(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;
Rectangle r(l, b);
cout << r.area_calc() << endl;
cout << r.peri_calc() ;
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
return Area::calc(length, breadth);
return Perimeter::calc(length, breadth);
Solution: Multiple Inheritance
Question 3
Consider the skeletal code given below. Marks: 3Fill up the blanks by following the instructions associated with it and complete the code, sothat 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) {}
// Declare the area function here
_________________________________
void printarea() { cout << this->area() << ":"; }
};
class Rectangle : public Polygon {
11
public:
Rectangle(int a, int b) : Polygon(a, b) {}
int area() { return width*height; }
};
class Triangle : public Polygon {
public:
Triangle(int a, int b) : Polygon(a, b) {}
int area() { return width*height / 2; }
};
int main() {
int h, w;
cin >> h >> w;
// Declare ppoly1 and ppoly2 as "pointer to Polygon" and dynamically allocate
// a Rectangle and a Triangle objects respectively held by these pointers
_________________________________ // Rectangle object of h and w
_________________________________ // Triangle object of h and w
ppoly1->printarea(); // For Rectangle object
ppoly2->printarea(); // For Triangle object
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; }
Polygon * ppoly1 = new Rectangle(h, w);
Polygon * ppoly2 = new Triangle(h, w);
Solution: Late binding occurs
Question 4
Fill the blank by defining the proper constructor where name of the parameter should be nc
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;
class A { protected: int ai;
public:
A(int i) : ai(i) {}
_______ void f() = 0; // Fill the blank or Remove blank
_______ void g() // Fill the blank or Remove blank
{ ++ai; }
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
_______ void g() // Fill the blank or Remove blank
{ A::g(); }
};
class C : public B { int ci;
public:
C(int i) : B(i), ci(i) {}
_______ void f() //Fill the blank or Remove blank
{ cout << ai << bi << ci; } // DO NOT EDIT THIS LINE
_______ void g() //Fill the blank or Remove blank
{ B::g(); }
};
int main() {
int x = 3 ;
int y;
cin >> y;
A *p[] = { new B(x), new C(y) };
for(int i = 0; i < sizeof(p) / sizeof(A*); ++i)
{ p[i]->g(); p[i]->f(); }
return 0;
}
Further, the input / output test case is as follows:
Public 1
Input: 2
Output: 43322
Public 2
Input: 23
Output: 43242323
Private
Input: 4
Output: 43544
Answer: virtual // virtual // virtual or blank // virtual or blank // virtual or blank// virtual or blank
Question 3
Consider the following code. write the proper definition of ”getArea()” in the editable sectionso that the test cases would pass . Marks: 2
9
#include <iostream>
using namespace std;
class Shape {
protected:
int width, height;
public:
// Write the getArea() function here
void setWidth(int w) { width = w; }
void setHeight(int h) { height = h; }
};
class Rectangle : public Shape {
public:
int getArea() { return (width * height); }
};
class Triangle : public Shape {
public:
int getArea() { return (width * height) / 2; }
};
int main(void) {
int x, y;
cin >> y >> x;
Rectangle Rect;
Triangle Tri;
Rect.setWidth(x);
Rect.setHeight(y);
Tri.setWidth(x);
Tri.setHeight(y);
Shape *shape[] = { &Rect, &Tri, 0 };
Shape **pShape = &shape[0];
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:
virtual int getArea() = 0;
Question 4
Consider the following code. Fill up the code in editable section to congratulate the Managerand the Clerk, so that outputs will be matched as given in the test cases. Marks: 2
Find out the output of the following program? Marks: 1
#include <iostream>
using namespace std;
int fun(int* ptr){
return (*ptr + 10);
}
void fun(int& ptr){
ptr = 100;
}
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 << " "; }
};
class Faculty : virtual public Person {
public:
Faculty(int x) :Person(x) {
cout << 3 * x << " ";
}
};
class Student : virtual public Person {
public:
Student(int x) :Person(x) {
cout << 3 * x << " ";
}
};
class TA : public Faculty, public Student {
public:
TA(int x) : Student(x), Faculty(x) {
cout << 5 * x << " ";
}
};
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 ta1is constructed and destructed. So object ta1 has two copies of all members of Person, thiscauses ambiguities. The solution to this problem is virtual keyword. We make the classesFaculty 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() {};
};
class D1: public Base
{
public:
virtual void function1() {};
};
class D2: public Base
{
public:
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
a) Base::function1() & D2::function2()
b) Base::function1() & D1::function2()
c) D1::function1()only
d) D1::function1() & D2::function2()
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 hiddenpointer 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 tothe class which points to an array of pointers to (virtual) functions called the Virtual FunctionTable (VFT)
Question 6
Look at the code given below. Identify the statements where correct use of staic cast operatorhas been done. MCQ, Mark 1
#include <iostream>
using namespace std;
int main(){
float f = 12.3;
float* pf = &f;
int n = static_cast<int>(f); // stmt-1
int* pn = static_cast<int*>(pf); // stmt-2
void* pv = static_cast<void*>(pf); // stmt-3
return 0;
}
a) stmt-1, stmt-2
b) stmt-2, stmt-3
c) stmt-1, stmt-3
d) stmt-1, stmt-2, 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:FailureSA, Marks: 1
#include <iostream>
using namespace std;
class Base { public: virtual ~Base() {} };
class Derived : public Base { };
int main() {
4
// Fill the blank by appropriate caste operator
Derived *pd = ___________ <Derived*>(new Base);
cout << (pd ? "Success": "Failure");
return 0;
}
Answer: dynamic cast
Solution: dynamic cast is used to cast a base pointer into a derived pointer. If the basepointer doesn’t point to an object of the type of the derived, it returns NULL pointer.
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;
struct A { virtual ~A() { } };
struct B : A { };
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 typederived 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 thestatic cast<Base>(*this).Action() call.
Question 10
static cast can be used for
1. Downcast
2. Upcast
3. Implicit conversions
4. User-defined conversions
Find out the correct statements. Marks: 1
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() {};
};
class Foo : public Base {
public:
virtual void DoIt() { cout << "12,"; };
void FooIt() { cout << "13,"; }
};
class Bar : public Base {
public:
virtual void DoIt() { cout << "14,"; }
void BarIt() { cout << "15:"; }
};
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) {
Base* base = CreateRandom(n);
base->DoIt();
Bar* bar = __________________(base);
Foo* foo = __________________(base);
if (bar)
bar->BarIt();
if (foo)
foo->FooIt();
}
return 0;
}
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:
Bar* bar = dynamic_cast<Bar*>(base);
Foo* foo = dynamic_cast<Foo*>(base);
Solution: The casts execute at runtime, and work by querying the object (no need to worryabout 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
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 matterwhat the type of the exception thrown. This can be used as a default handler that catches allexceptions 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);
cout << k << endl;
cout << n << endl;
return 0;
}
a) int GetMax (int a, int b)
b) template <class T>T GetMax (T a, T b)
c) template <class T >class GetMax
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
void myFunction(int test) {
try{
if (test)
throw test;
else
throw "Value is zero";
}
catch (int i) {
cout << "CaughtOne " ;
}
catch (const char *str) {
cout << "CaughtString ";
}
}
int main() {
2
myFunction(1);
myFunction(2);
myFunction(0);
myFunction(3);
return 0;
}
a) CaughtOne CaughtOne CaughtString CaughtString
b) CaughtOne CaughtString CaughtString CaughtOne
c) CaughtOne CaughtOne CaughtOne CaughtOne
d) CaughtOne CaughtOne CaughtString CaughtOne
Answer: d)Solution: Multiple handlers (i.e., catch expressions) can be chained; each one with a differentparameter type. Only the handler whose argument type matches the type of the exceptionspecified 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 caughtC++ Exception
b) C++ ExceptionMyException caught
c) Exception caughtC++ Exception
3
d) C++ ExceptionMyException caughtException caught
Answer: a)Solution: Multiple handlers (i.e., catch expressions) can be chained; each one with a differentparameter type. Only the handler whose argument type matches the type of the exceptionspecified 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
b) caught Small Trouble
c) caught Big Trouble
d) default
Answer: a)
4
Solution: Multiple handlers (i.e., catch expressions) can be chained; each one with a differentparameter type. Only the handler whose argument type matches the type of the exceptionspecified 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 differentparameter type. Only the handler whose argument type matches the type of the exceptionspecified 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;
----------------------- // Fill in the blank
int arrMin(T arr[], int n) {
int m = max;
for (int i = 0; i < n; i++)
if (arr[i] < m)
m = arr[i];
return m;
}
int main() {
int arr1[] = {10, 20, 15, 12};
int n1 = sizeof(arr1)/sizeof(arr1[0]);
char arr2[] = {1, 2, 3};
int n2 = sizeof(arr2)/sizeof(arr2[0]);
cout << arrMin<int, 10000>(arr1, n1) << endl;
cout << arrMin<char, 256>(arr2, n2);
return 0;
}
------------
Output:
10
1
a) template <T, int max>
b) template <T>, int max
c) template <class T>, int max
d) template <class T, int max>
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;
// Define Swap() function here
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);
cout << a << " " << b << " ";
cout << s << " " << t << " ";
cout << mr << " " << ms ;
return 0;
}
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;
class myexception : public exception
{
// Define the Proper function which will return a string "DivideByZero"
} 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
virtual const char* what() const throw()
{
return "DivideByZero";
}
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
March 22, 2017
Question 1
Using friend operator function, which set of operators can be overloaded? Mark 1
a. � , � , <, >, ==, <=,>=
b. + , - , / , *
c. = , ( ) , [ ] , ->
d. && , = , * , ->Answer: aExplanation: 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. 3Answer: cExplanation: 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();
}
Output of the Code is
a. Compilation error
b. 20 In Display
c. 20 In Display Destroyed
d. 0 In DisplayAnswer: cExplanation: 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;
}
Output of the Code is
a. 10 10
b. 50 50
c. Error: Cannot Link the namespaces
d. Compilation error: Invalid Namespace ResolutionAnswer: bExplanation: Using namespace EX to access x and y
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;
}
a) int Test t.x = 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
b) Compilation Error: print cannot access x as it is private
c) Compilation Error: illegal parameter passing in print
d) Compilation Error: Const parameter cannot be passed in friend function
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 +
d) Compilation Error: Ambiguous declaration
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; }
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.
b) Static data member must be initialized in a source file.
c) It is Associated with object not with class.
d) It can be accessed as a member of any object of the class
Answer: c)Explanation: As per definition of static data members
Programming Assignment
Question 1
Write down the required keywords in the first blank. Fill the rest of the blank by callingthe user defined function abs() or library function abs(), So that the given test cases will besatisfied 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;
}
Answer: namespace // NS::abs//NS::abs//NS::abs // abs//abs//absExplanation: As per syntax of namespaces, refer slides
a. Input: -203, -69, 9
Output: 0 69 9
203 69 9
b. Input: 178, 45, 0
Output: 0 45 0
178 45 0
c. Input: -114, 20, 2
Output: 114 20 2
114 20 2
Question 2
Here S and R Represent two geometric class, Square and Rectangle respectively. Our objectiveis 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;
}
Answer: friend class R// R::convertExplanation: If a class needs to access the private members(width and height) of a differentclass, it should be a declared as a friend class.
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 Bykeeping 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;
}
Answer: MyClass(int d): data(d) // *this // MyClass operator++(int) // t //Explanation: As per operational semantics of the post and pre increment operators, checkslides.
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;
}
Answer: friend void display(const MyClass &a); // const MyClass &aExplanation: To access the private member of a class, a non member function(in this casedisplay) should be a declared as a friend function. Check the slides
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 aboutstaticMarks 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;
}
Answer: static void // int MyClass::x = 1Explanation: Static variables can be initialised outside the scope of the main withoutconstructing objects. It remains live outside main.