Exercise 1:
Given the following class definitions:
class X {
public:
int b;
X( ) { a = b = c = 0;}
void print( ) { cout << a << b << c;}
protected:
int c;
private:
int a;
};
|
class Y : public X { protected: int d; private: int e; public: Y( ) : X() { d = e = 0; } void print() { cout << d << e;} }; |
(1) Let x be an object of class X and y be an object of class Y, list data members in objects x and y:
(2) In class Y, can we change the value of the variable c?
Can we print out the value of c in class Y?
Which variables’ values cannot be printed out in class Y?
Modify definition of class Y such that we can print all the values of its data members.
(3) Let Z be a class defined as:
class Z : protected Y {
};
and let z be an object of class Z. List all the data members in z with their access permissions.
(4) Modify the definition of class Z in (3) by adding a constructor to initialize all data members and a print function to print out all data members of Z.
Exercise 2:
Given the following class definitions:
class X {
public:
X( ) { a = b = c = 0;}
void print( ) { cout << a << b << c;}
protected:
int c;
private:
int a, b;
};
|
class Y : public X { protected: int d; private: int e; public: Y( ) : X() { d = e = 0; } void print( ) { cout << d << e; } }; |
Based on the following function f:
(a) identify and mark out statements that are invalid.
(b) show what are printed based on valid statements only.
void f( )
{
X x, *px;
Y y, *py;
px = &y;
py = &x;
x.c = 2;
x.b = 2;
y.d = 3;
y.c = 2;
y.b= 1;
x.print();
y.print();
py->c = 5;
px->e = 1;
px->b = 3;
px->print();
py->print();
}