C++ Quiz no.4

Fix the following code so the B is destroyed properly:

struct A {};
struct B: A {};

int main()
{
   A * p = new B;
   delete p;
}

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

Answer to C++ Quiz no.3

#include <iostream>
class example
{
 public:
   example& operator+(const example& obj1);
};

example &example::operator+(const example& obj2)
{
 return *this; //Every object in C++ has access to its own address through an important pointer called this pointer.
}

int main(void)
{
  example a, b;
  example* c;
  c = &(a + b);
  //std::cout<< &c <<" "<<"\n";
}
Advertisements

C++ Quiz no.3

Write minimal implementation of A and B such that the following expression to be legal:

A x;
B y;
y = & ( x + 1);

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

Answer to C++ Quiz no.2

#include <iostream>
using std::cout;

struct Row
{
 int a[3];
 Row(int x) { a[0] = x; a[1] = ++x; a[2] = ++x; }
 int * begin() { return a; } // a == &a[0]
 int * end() { return a + 3; } // a + 3 == &a[3]
};

struct Matrix
{
 Row r[3] = { 1, 4, 7 };
 Row * begin() { return r; }
 Row * end() { return r + 3; }
};

int main()
{
 Matrix m;
 for ( auto r : m ) //in pre-C++11 == for ( Row * r = m.begin(); r!= m.end(); ++r) // inside the body we need to use *r which is type Row
 {
  for ( auto e : r )
    cout << ' ' << e;
  cout << '\n';
 }
}

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;
}

C++ Quiz no.1

The next posts will include C++ related stuff due to the current Mazonka-based mentoring. Here is a simple quiz to start with:

Is there something wrong with the following code? If yes, can you explain why?

{
 const int c = 1;
 int * p;
 const int ** q = &p; // q points to p
 *q = &c; // now p points to c
 *p = 10; // modify c !
}

Answer will be provided to the next post.