C++ Quiz no.2

Implement a Matrix class for which

Matrix m;
for( auto r : m )
{
   for( auto e : r )
      cout << ' ' << e;
   cout << '\n';
}

prints

1 2 3
4 5 6
7 8 9

————————————

Answer to C++ Quiz no.1

There is an invalid conversion from [int** -> const int**] although [int* -> const int*] is a legal conversion. Trying to increase constness with [int** -> const int**], we introduce a gap between pointer q and object c (i.e. a pointer p between our pointer q and the object c). In order to cover this hole, the following two efforts introduce errors for different reasons (included as comments):

int main ()
{
  const int c = 1;
  const int * p;
  const int ** q = &p; 
  *q = &c; 
  *p = 10; // error: assignment of read-only location (*p) i.e. no way to deceive const restrictions (without explicit conversions).
}
int main ()
{
  const int c = 1;
  int * p;
  const int * const* q = &p;
  *q = &c; // error: assignment of read-only location (*q) i.e. (*q) is a const variable and cannot be modified.
  *p = 10;
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s