0% found this document useful (0 votes)
23 views16 pages

C++ Programming Assignment Week 4

Modern C++ NPTEL Assignment

Uploaded by

Sheryl Viniba
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views16 pages

C++ Programming Assignment Week 4

Modern C++ NPTEL Assignment

Uploaded by

Sheryl Viniba
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Programming in Modern C++: Assignment Week 4

Total Marks : 25

Partha Pratim Das


Department of Computer Science and Engineering
Indian Institute of Technology Kharagpur, Kharagpur – 721302
[Link]@[Link]

February 7, 2024

Question 1
Consider the following program. [MSQ, Marks 2]

#include<iostream>
using namespace std;

class Test{
int x;
public:
Test(int _x) : x(_x) {}
________________________; //Line-1
};
class ReTest{
int d;
public:
ReTest(int x) : d(x) {}
void update(const Test& r){
cout << (d + r.x);
}
};

int main(){
Test t(10);
ReTest rt(20);
[Link](t);
return 0;
}

Fill in the blank at LINE-1 so that the program will print 30.

a) friend class ReTest

b) class friend ReTest

c) static class ReTest

d) const class ReTest

1
Answer: a)
Explanation:
The ReTest class member function update() is accessing a private member of the class Test.
So, the class ReTest has to be a friend of class Test. So, the correct option is a).
Intentionally made as MSQ

2
Question 2
Consider the following code segment. [MCQ, Mark 2]

#include <iostream>
using namespace std;
int var = 0;
namespace Test {
int var = 2;
}
int main() {
________________________; // LINE-1
int var = 1;
{
cout << ::var << var << Test::var;
}
return 0;
}

Fill in the blank at LINE-1 so that the program will print 012.

a) using Test

b) namespace Test

c) using namespace Test

d) using namespace Test::var

Answer: c)
Explanation:
Syntax to include a namespace in the main function is defined as using namespace Test so
that the content can be used in the scope.

3
Question 3
Consider the following code segment. [MSQ, Marks 2]

#include<iostream>
using namespace std;
class Test{
______________ x; //LINE-1
public:
Test(double _x) : x(_x) {}
void set(double a) const{
x = a;
}
void print() const{
cout << x << endl;
}
};
int main(){
const Test t(3.14);
[Link](9.81);
[Link]();
return 0;
}

Fill in the blank at LINE-1 so that the program will print 9.81.

a) mutable double

b) const double

c) static double

d) double mutable

Answer: a), d)
Explanation:
To change the value of the data member of a constant object, we need to declare the data
member as mutable. So, the syntax is mutable double or double mutable.

4
Question 4
Consider the following code segment. [MCQ, Marks 2]

#include<iostream>
using namespace std;
class Test{
static int s;
public:
void incr(int x){ s = s + x; }
void print(){ cout << s; }
};
int Test::s = 10;
int main(){
Test t1;
[Link](5);
Test t2;
[Link](10);
[Link]();
return 0;
}

What will be the output?

a) 10

b) 15

c) 20

d) 25

Answer: d)
Explanation:
The static data member Test::s is initialized during the program startup and is shared by
both objects t1 and t2 of the class Test. Hence, the data member is initialized as 10 during
the start of the main function. It is incremented two times when the incr() function is called
for both objects. Hence, the print() function will print 25.

5
Question 5
Consider the following code segment. [MCQ, Marks 2]

#include<iostream>
using namespace std;
class myClass{
static int a;
public:
void incr(){
a = a + 5;
}
static void display(){
cout << a;
}
};
int myClass::a = 0;
int main(){
myClass m;
[Link]();
__________________; //LINE-1
return 0;
}

Fill in the blank at LINE-1 so that the program will print 5.

a) display()

b) myClass::display()

c) [Link]()

d) myClass->display()

Answer: b)
Explanation:
When a function is declared as static, it can be called using the class name. The syntax is
myClass::display().

6
Question 6
Consider the following code segment. [MCQ, Marks 2]

#include<iostream>
int main(){
char greet[] = "Hello";
cout << greet; //LINE-1
return 0;
}

Change the LINE-1 with the appropriate option so that the program will run successfully.

a) using cout << greet;

b) using std::cout << greet;

c) std::cout << greet;

d) [Link] << greet;

Answer: c)
Explanation:
cout is a predefined object in namespace std. In order to call cout function, we need to specify
that cout belongs to the std namespace. The correct syntax for the same is std::cout <<
greet; i.e. option c).

7
Question 7
Consider the following code segment. [MSQ, Marks 2]

#include<iostream>
using namespace std;
namespace n1{
int a = 1;
int b = 2;
}
namespace n2{
int c = 3;
int d = 4;
}

int main(){
using namespace n2;
cout << a << endl; //LINE-1
cout << n1::b << endl; //LINE-2
cout << n2::c << endl; //LINE-3
cout << d << endl; //LINE-4
return 0;
}

Which line/s will generate a compilation error?

a) LINE-1

b) LINE-2

c) LINE-3

d) LINE-4

Answer: a)
Explanation:
The variable a is declared within namespace n1 and is not accessible within the scope of the
main function because the namespace n1 is not included. Hence, LINE-1 will give an error.
The variable b is accessed using the namespace n1, which is perfectly fine. Hence, LINE-2 will
not give any error.
The variable c is accessed using the namespace n2, which is also fine and will not give any
error.
The variable a is declared in namespace n1, and it is included in the program. Hence, LINE-1
will not give any error.
This question is intentionally made as MSQ.

8
Question 8
Consider the following code segment. [MCQ, Marks 2]

#include <iostream>
using namespace std;
class classA{
int a=5;
public:
classA(int _a) : a(_a) {}
int get() { return a; }
};
class classB{
static classA c1;
public:
static int get(){
return [Link]();
}
};
int main(void){
cout << classB::get();
return 0;
}

What will be the output/error?

a) 0

b) 5

c) Compilation error: inaccessible object c1

d) Compilation error: undefined reference classB::c1

Answer: d)
Explanation:
The static variable c1 in classB needs to be initialized globally in order to use it. But there is
no initiation for c1 in the program. Thus, it gives a compilation error as Undefined reference
classB::c1.

9
Question 9
Consider the following code segment. [MCQ, Marks 2]

#include<iostream>
using namespace std;
class Test{
static int a;
public:
Test() { a++; }
static int get(){ return a; }
};
int Test::a = 0;
int main(){
cout << Test::get() << " ";
Test t[4];
cout << Test::get();
return 0;
}

What will be the output?

a) 0 3

b) 0 4

c) 1 3

d) 1 4

Answer: b)
Explanation:
The lifetime of a static class variable will be throughout the program. So, the static data
member of the class is initialized with 0 when the get() function is called. The first cout
statement prints 0. Next, the initializations of another four objects, increment the static
variable four times. Hence second cout statement prints 4.

10
Programming Questions

Question 1
Consider the program below.

• Fill in the blank at LINE-1 with appropriate keyword,

• Fill in the blank at LINE-2 with appropriate return type of the function,

• Fill in the blank at LINE-3 with the appropriate initialization statement of the static
variable obj.

The program must satisfy the given test cases. Marks: 3

#include<iostream>
using namespace std;
class myClass{
char c;
_______ myClass *obj; //LINE-1
myClass(char x) : c(x) { }
public:
________________ create(char x){ //LINE-2
if(!obj)
obj = new myClass(x);
return obj;
}
void show();
};
_____________________________ //LINE-3
void myClass::show(){
cout << c;
}
int main(){
int x, y;
myClass *s1, *s2;
cin >> x >> y;
s1 = myClass::create(x);
s2 = myClass::create(y);
s1->show();
s2->show();
return 0;
}

Public 1
Input: 97 98
Output: aa

Public 2
Input: 65 56
Output: AA

11
Private
Input: 101 110
Output: ee

Answer:
LINE-1: static
LINE-2: static myClass*
LINE-3: myClass *myClass::obj = 0;
Explanation:
The variable object should be declared as static so that the first instance of myClass is always
present throughout the program. The function create() returns the member object.
So, LINE-2 is filled as static myClass* . The static member of class should be initialized at
LINE-3 with myClass *myClass::object = 0.

12
Question 2
Consider the following program.

• Fill in the blank at LINE-1 with the appropriate statement such that the global function
can access private class members,

• Fill in the blank at LINE-2 with the appropriate statement such that the global function
can access private class members

The program must satisfy the sample input and output. Marks: 3

#include<iostream>
using namespace std;
class A{
int x;
public:
A(int _x) : x(_x){ cout << "Class A: "; }
______________________________ //LINE-1
};
class B{
int x;
public:
B(int _x) : x(_x){ cout << "Class B: "; }
_______________________________ //LINE-2
};
void print(int a, int b){
if(a == 1)
cout << A(b).x;
else
cout << B(b).x;
}
int main(){
int a, b;
cin >> a >> b;
print(a,b);
return 0;
}

Public 1
Input: 1 5
Output: Class A: 5

Public 2
Input: 2 3
Output: Class B: 3

Private
Input: 1 -1
Output: Class A: -1

13
Answer:
LINE-1: friend void print(int, int);
LINE-2: friend void print(int, int);
Explanation:
The global function print() is accessing private data members of both classes A and B. This
can be possible only when the function is friend of both classes. So, LINE-1 and LINE-2 will
be filled as friend void print(int, int);

14
Question 3
Consider the following program.
• Fill in the blanks at LINE-1, LINE-2, LINE-3 and LINE-4 with appropriate keywords
The program must satisfy the sample input and output. Marks: 3
#include<iostream>
using namespace std;
class Emp{
int id;
________ double basic; //LINE-1
________ double salary; //LINE-2
public:
Emp(int i, double b, double s=0) : id(i), basic(b), salary(s){ }
void setBasic(double b) _____{ //LINE-3
basic = b;
}
_______ double calculate(const Emp&); //LINE-4
};
double calculate(const Emp &e){
[Link] = [Link] + [Link] * 0.5;
return [Link];
}
int main(){
int a;
double b,c;
cin >> a >> b >> c;
const Emp e(a,b);
cout << calculate(e) << " ";
[Link](c);
cout << calculate(e);
return 0;
}

Public 1
Input: 1 1000 400
Output: 1500 600

Public 2
Input: 5 2000 200
Output: 3000 300

Private
Input: 2 5400 320
Output: 8100 480

Answer:
LINE-1: mutable
LINE-2: mutable
LINE-3: const

15
LINE-4: friend
Explanation:
In this program, we attempt to modify the values of the data members belonging to a constant
object. It can be done if the blanks at LINE-1 and LINE-2 are filled with keyword mutable.
The function calculate() is called using constant class object. It is done only when the blank
at LINE-3 is filled with const keyword. To access private data members from global function,
the function needs to be declared as friend at LINE-4.

16

Common questions

Powered by AI

'Const correctness' is compromised when objects intended to be immutable are modified. This can occur either via mutable members or when const-cast operations are improperly used. Proper handling includes using the 'mutable' keyword for members that need to change even in 'const' objects, but logical const correctness should still ensure that what is supposed to remain unchanged logically, does not change .

In C++, the 'friend' keyword allows a function or another class to access the private and protected members of the class where it is declared as a friend. This breaks the encapsulation principle of object-oriented programming by allowing external functions or classes to modify private data. For example, in the given programs, the 'friend' keyword is used to give certain functions access to private members of the classes .

Order of initialization is crucial in C++ as it determines how the class members and objects are set up before use. Logical errors arise if objects are accessed before proper initialization, leading to undefined behaviors or access violations. Ensuring correct construction and initialization sequence prevents such errors. This is evident in setups where static objects in classes need prior initialization to prevent compilation errors .

Using 'friend' functions in C++ breaks encapsulation by allowing external entities to access private members, thus violating data hiding principles of object-oriented programming. While it can be necessary for certain operations, such as operators overloading that requires access to internal states, it should be used sparingly as overuse can lead to poor encapsulation and tightly coupled code .

In C++, static data members must be initialized outside the class definition because they are shared across all instances of the class. Static members are not part of the individual class instances but are instead shared globally across all instances, so one initial value needs to be set. For example, 'static int s' in class 'Test' is initialized outside the class as 'int Test::s = 10; .

The 'mutable' keyword in C++ allows a particular class data member to be modified even if it is part of an object that is declared as 'const'. This is useful when a logical constness is maintained for an object while allowing certain variables within the object to change. In the document, it was required to modify members of a constant class object, thus 'mutable' was used .

An "undefined reference" error occurs with static class members when they are declared but not defined outside the class definition. Static members must be defined in a global scope, as demonstrated in class 'classB', where static member 'c1' was not properly initialized globally, leading to a compilation error .

A static function in a class belongs to the class itself rather than any object instance. It cannot access non-static data members or member functions directly. Being callable without an instance object, static functions are generally used for utility functions related to the class. For instance, 'myClass::display()' is called using 'myClass::display();' as it is a static function .

Improper use of global variables can lead to unexpected behaviors and debugging difficulties due to their global accessibility. Scoping issues, such as using the wrong variable when multiple variables of the same name exist in different scopes, can occur without clear resolution or qualification (like '::var' for global scope). Correct use of scope resolution operators avoids such conflicts .

Namespaces are used in C++ to organize code into logical groups and to prevent name conflicts. For instance, two different libraries may have functions with the same name, but the use of namespaces ensures that they are used correctly within their respective scopes without conflict. Using the 'using namespace' directive correctly allows the compiler to distinguish which entities are being referred to in the code .

You might also like