Classes And Objects In C Plus Plus - Study Mode
[#151] What will be the output of the following C++ code? #include <iostream>
#include <string>
using namespace std
class test
{
public:
operator string ()
{
return "Converted"
}
}
int main()
{
test t
string s = t
cout << s << endl
return 0
}
Correct Answer
(A) converted
[#152] What will be the output of the following C++ code? #include <iostream>
#include <string>
#include <cstring>
using namespace std
int main()
{
string s('a')
cout<<s
return 0
}
Correct Answer
(C) Error
[#153] What will be the output of the following C++ code? #include <iostream>
using namespace std
class sample
class sample1
{
int width, height
public:
int area ()
{
return (width * height)
}
void convert (sample a)
}
class sample
{
private:
int side
public:
void set_side (int a)
{
side = a
}
friend class sample1
}
void sample1::convert (sample a)
{
width = a.side
height = a.side
}
int main ()
{
sample sqr
sample1 rect
sqr.set_side(6)
rect.convert(sqr)
cout << rect.area()
return 0
}
Correct Answer
(D) 36
[#154] What will be the output of the following C++ code? #include <iostream>
using namespace std
class Rect
{
int x, y
public:
void set_values (int,int)
int area ()
{
return (x * y)
}
}
void Rect::set_values (int a, int b)
{
x = a
y = b
}
int main ()
{
Rect recta, rectb
recta.set_values (5, 6)
rectb.set_values (7, 6)
cout << "recta area: " << recta.area()
cout << "rectb area: " << rectb.area()
return 0
}
Correct Answer
(A) recta area: 30 rectb area: 42
[#155] Which access specifier allows members of a class to be accessed only by member functions of the same class and its derived classes in C++?
Correct Answer
(A) protected
Explanation
Solution: Access specifiers in C++ determine the visibility and accessibility of class members. The protected access specifier allows members of a class to be accessed by: 1. Member functions of the same class 2. Member functions of its derived (child) classes This makes protected different from private , which restricts access only to the class itself, and from public , which allows access from anywhere. Now let’s see why the other options are incorrect: Option B: public — Members are accessible from anywhere in the program , which is more permissive than required by the question. Option C: private — Members are accessible only within the same class , not by derived classes, so this is too restrictive. Option D: friend — friend is not an access specifier
it is a keyword used to allow a specific external function or class to access private or protected members of another class. It doesn’t define a general access level. Conclusion: The protected access specifier is the one that allows class members to be accessed within the same class and its derived classes. Hence, the correct answer is Option A: protected .