if a constructor OR public member function throws an exception, will the objects destructor be called automatically?

Why not try it and see for yourself:

#include <iostream>

struct Foo {
  Foo(bool shouldThrow) { 
    if(shouldThrow) {
      std::cout << "Foo Constructor called, throwing exception..." << std::endl;
      throw 42;
    } else {
      std::cout << "Foo Constructor called, no throwing anything :)" << std::endl;
    };
  };
  ~Foo() {
    std::cout << "Foo Destructor called!" << std::endl;
  };

  void someMethod() {
    throw 69;
  };

};

struct Bar {
  Foo f;
  Bar() : f(false) {
    std::cout << "Bar Constructor called, throwing exception..." << std::endl;
    throw 17;
  };
  ~Bar() {
    std::cout << "Bar Destructor called!" << std::endl;
  };
};


int main() {
  std::cout << "\nTrying to create object Foo(true)..." << std::endl;
  try {
    Foo f(true);
  } catch (int e) {
    std::cout << "Caught exception number " << e << std::endl;
  };

  std::cout << "\nTrying to create object Foo(false) and calling someMethod..." << std::endl;
  try {
    Foo f(false);
    f.someMethod();
  } catch (int e) {
    std::cout << "Caught exception number " << e << std::endl;
  };

  std::cout << "\nTrying to create object Foo(true) dynamically..." << std::endl;
  try {
    Foo* fp = new Foo(true);
    delete fp;
  } catch (int e) {
    std::cout << "Caught exception number " << e << std::endl;
  };

  std::cout << "\nTrying to create object Foo(false) dynamically and calling someMethod..." << std::endl;
  try {
    Foo* fp = new Foo(false);
    fp->someMethod();
    delete fp;
  } catch (int e) {
    std::cout << "Caught exception number " << e << std::endl;
  };

  std::cout << "\nTrying to create object Bar..." << std::endl;
  try {
    Bar b;
  } catch (int e) {
    std::cout << "Caught exception number " << e << std::endl;
  };

  return 0;
};
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.