questions - krishnaramb/cplusplus GitHub Wiki

Questions

Q1. Write you own version of post and pre-increment function? Please note that for pre-increment: l-value goes in and l-value comes out while for the post-increment, l-value goes in and r-value comes out.

int post_increment++(int &x)
{
  //l-value comes in , r-value goes output
  int temp = x;
  x = x+1;
  return temp;
}
int & pre_increment++(int &x)
{
  //l-value comes in, l-value goes out
  x = x +1;
  return x;
}

Q2. How can I handle a constructor that fails?
throw an exception. Constructors don't have a return type, so it's not possible to use return codes. The best way to signal constructor failure is therefore to throw an exception.

Q3. Stack Unwinding in C++??
Q4. How can I handle a destructor that fails?
Q5.What's the order that local objects are destructed?
A> In reverse order of construction: First constructed, last destructed.

  • Q: What's the order that objects in an array are destructed? A: In reverse order of construction: First constructed, last destructed. In the following example, the order for destructors will be a[9], a[8], ..., a[1], a[0]:
void userCode()
{
Fred a[10];
...
}
  • Q: Can I overload the destructor for my class? A: No. You can have only one destructor for a class Fred. It's always called Fred::~Fred(). It never takes any parameters, and it never returns anything. You can't pass parameters to the destructor anyway, since you never explicitly call a destructor (well, almost never).

  • Q: Should I explicitly call a destructor on a local variable? A: No!

  • Q: But can I explicitly call a destructor if I've allocated my object with new? NO. Unless you used placement new, you should simply delete the object rather than explicitly calling the destructor. For example, suppose you allocated the object via a typical new expression:

Fred* p = new Fred();

Then the destructor Fred::~Fred() will automatically get called when you delete it via:

delete p; // Automagically calls p->~Fred()

You should not explicitly call the destructor, since doing so won't release the memory that was allocated for the Fred object itself. Remember: delete p does two things: it calls the destructor and it deallocates the memory.