Question 31
MediumIn C++, how do a class and a struct differ?
- A.
Popular companies
Prepare company by company
Hiring pattern, syllabus, past questions and mocks for each company.
All companiesPractice by subject
Object-Oriented Programming
In C++, how do a class and a struct differ?
There is no difference at all
Members of a class are private by default; members of a struct are public by default
A class cannot have data members
A struct cannot have methods
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
class Bag:
items = []
def add(self, x):
self.items.append(x)
a = Bag()
b = Bag()
a.add(1)
b.add(2)
print(a.items, b.items)
[1, 2] [1, 2]
[] [1, 2]
Sign up free to see the answer and a step-by-step explanation.
What is the difference between a class variable and an instance variable?
There is no difference
Instance variables are shared by all objects
Class variables can only be strings
A class variable is shared by all instances; each instance has its own copy of an instance variable
Sign up free to see the answer and a step-by-step explanation.
Can a static method access instance (non-static) members directly?
Only in Python
Only if it is private
No, because it isn't called on any particular object
Yes, always
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
class Counter:
count = 0
def __init__(self):
Counter.count += 1
self.id = Counter.count
a = Counter(); b = Counter(); c = Counter()
print(a.id, c.id, Counter.count)
1 3 3
3 3 3
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
class Box:
items = []
def add(self, x):
self.items.append(x)
p = Box(); q = Box()
p.add(1); q.add(2)
print(len(p.items), len(q.items))
1 2
1 1
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
class P:
n = 5
a = P(); b = P()
a.n = 10
P.n = 20
print(a.n, b.n)
10 5
20 20
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
#include <iostream>
using namespace std;
class Point {
public:
int x, y;
Point(int a, int b) : x(a), y(b) {}
};
int main() {
Point p(2, 3);
Point q = p;
q.x = 9;
cout << p.x << " " << q.x;
}
9 2
9 9
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
#include <iostream>
using namespace std;
class A {
public:
static int n;
A() { n++; }
};
int A::n = 0;
int main() {
A x, y;
A *p = new A();
A arr[2];
cout << A::n;
delete p;
}
5
2
Sign up free to see the answer and a step-by-step explanation.
What is the output of this code?
class T:
def __init__(self, v):
self.v = v
a = T(1)
b = a
b.v = 7
print(a.v, a is b)
7 True
1 True
Sign up free to see the answer and a step-by-step explanation.
[1] [2]
[1, 2] []
0 2 3
1 1 3
2 2
0 0
5 20
10 20
2 2
2 9
3
4
1 False
7 False