Practice Problem of Classes
Practice Problem of Classes
Practice Problem of Classes
a) What would be the output produced by executing the following C++ code? Identify errors, if any
(Either write output or error , Both will not be acceptable).
#include <iostream>
using namespace std;
class Number {
private:
int n;
public:
Number() : n(0) {
cout << n;
}
01222
Page 1 of 8
b) What would be the output produced by executing the following C++ code? Identify errors, if any
(Either write output or error, both will not be acceptable).
#include <iostream>
using namespace std;
class Memory {
float capacity;
public:
Memory(int cap = 1) {
capacity = cap;
cout << " Added Memory of Capacity= "
<< capacity << " G " << endl;
}
~Memory() {
cout << " Removed Memory of Capacity= "
<< capacity << " G " << endl;
}
};
class Core {
float speed;
public:
Core(float speed_ = 3.3) {
speed = speed_;
cout << " Added 1 Core of Speed= "
<< speed << " GHz " << endl;
}
~Core() {
cout << " Removed 1 Core of Speed= "
<< speed << " GHz " << endl;
}
};
class Processor {
const int ncores;
Core cores[4];
public:
Processor() :
ncores(4) {
cout << " Added a Processor of "
<< ncores << " Cores " << endl;
}
~Processor() {
cout << " Removed a Processor of = "
<< ncores << " cores " << endl;
}
};
class Mobile {
Memory m;
Processor p;
public:
Mobile() {
cout << " Building a Mobile " << endl;
Page 2 of 8
}
~Mobile() {
cout << " Destroying a Mobile " << endl;
}
};
int main() {
Mobile m; cout << " :) The End " << endl; }
Page 3 of 8
c) What would be the output produced by executing the following C++ code? Identify errors, if any
(Either write output or error, both will not be acceptable).
#include <iostream>
#include <cassert>
using namespace std;
class Number {
public:
static int n;
Number() {cout << n++<<endl; }
~Number(){cout<<--n;}
};
int main(){
Number a, b(9), c(a);
fun(b);
return 0;
}
0
9
9
9
9
4321
Page 4 of 8
d) What would be the output produced by executing the following C++ code? Identify errors, if any
(Either write output or error, both will not be acceptable).
#include <iostream>
using namespace std;
class Integer {
public:
Integer() : n(new int) { *n=5;}
void increase() { *n += 1; } };
int main(){
b.increase();
c.display();
b.display(); }
1 1 6 6
Page 5 of 8
#include <iostream>
using namespace std; A::A(A &temp)
{
class A{ p= new int;
int *p; *p = *(temp.p);
static int a; }
8
8
8
12
#include <iostream>
using namespace std; A::A(A &temp)
{
class A{ p= new int;
int *p; *p = *(temp.p);
static int a; }
Page 7 of 8
#include <iostream>
using namespace std; A::A(int a)
{
int global = 9; this->a = a;
(this->a)++;
class A{
int a,b; b = this->a;
static int x; x--;
static int* p; cout << a <<endl;
p = &(this->a);
public:
A(); }
A(int);
A(int, int); A::A(int a, int b)
}; {
this->a = a;
int A::x = 19; this->b = 2;
int* A::p = &global; cout << a << endl;
x++;
A::A() cout << this->b << endl;
{ cout << *p;
cout << 1<<endl;
x+5; }
} int main() {
A obj1(3),obj4;
A obj2 = obj1;
Page 8 of 8