Vous êtes sur la page 1sur 2

Note: Answer Question 1 and select either Q2 or Q3.

Question 1 (40 marks):


Write the required C++ code to accomplish the following tasks:

(i) write the constructor definition for class A, so that each object of A and B will be initialized
correctly.

class B {
float y;
public:
B (float); // only this constructor is provided for B
};

class A {
int x;
B b;

};
(ii) The following is a declaration of class Array which contains an array of integers.
class Array {
int size; // size of the array
int* ptr; // pointer to first element of array
public:
Array (int=10); // default constructor
~Array();
//…
};

a. write a default constructor definition for class Array, in which ptr is initialized to point to an
array of zeros of any size . The default size of the array is 10.

b. Write a definition for the destructor of class Array that properly destruct the object, and free all
the memory allocated for the object.
(iii) Write a full C++ program that keeps printing the multiples of the integer 2 (ex. 2, 4, 8, 16, 32,
64…). You need to use an infinite loop to perform this task.

Question 2 (30 marks):


Consider the following definitions and show exactly the output of the program.
# include <iostream>
class Person
{
int energy;
public:
Person (int e=100 ) { energy = e; }
void eat () { energy++; }
void sleep () { energy += 2; }
void stand () { energy--; }
void jump () { energy - = 3; }
void print () { cout << energy <<endl; }
};

void main (void)


{
Person Salem;
Person Muna (200);
Person Rami;
Person Nahid (300);

Nahid.eat();
Nahid.sleep();
Rami = Nahid;
Rami.jump();

for (int i = 0; i < 10; i++)


Salem.jump();
Salem.eat();

for (int i = 0; i < 5; i++)


{
Muna.sleep();
Muna.stand();
}
cout << "\n Salem Energy = " << Salem.print();
cout << "\n Muna Energy = " << Muna.print();
cout << "\n Rami Energy = " << Rami.print();
cout << " \n Nahid Energy = " << Nahid.print();
}

Question 3 (30 marks):


Find the errors and correct them in each of the following:
a) char *string; string = new char [20]; free (string);

b) class Example { public: Example (int y = 20) { data = y; }


int getIncrementData () const { return ++data; }
static int getcount () { cout << “Data is “ << data << endl;
return count; }
private: int data; static int count; };

c) class Time { public: void print ();


private: int h = 0; int m = 0; int s = 0 ; };

d) int sum (int x, int y) { int result; result = x + y;}


e) for (k = 0.1; k != 1.0; k +=0.1) cout << k << endl;

Vous aimerez peut-être aussi