Skip to main content

Posts

Exceptions in Destructors

When dog objects in main() go out of scope, it invokes destructor. Since destructor throws an exception, due to multiple exception condition program crashes. class dog { public: string m_name; dog(string name)  {  m_name = name;  cout << name << " is born." << endl;  } ~dog()  {  cout << m_name << " is distroied.\n" << endl; throw 10; } }; int main() { try { dog dog1("Henry"); dog dog2("Bob"); } catch (int e) { cout << e << " is caught" << endl; } return 1; } Solution 1:   Destructor swallow the exception ~dog() {        try {          // Enclose all the exception prone code here       } catch (MYEXCEPTION e) {          // Catch exception       } catch (...) {       }    } Solution 2:   Move ...

Shared Pointer : Alternative to Virtual Destruct

When a base class points to a derived class object and when delete gets called on pointer then only base class destructor gets called. Solution 1:  TO overcome this issue, make base class destructor as virtual. With this change, both the derived class and base class destructor gets called. Solutions 2 : Using Shared_ptr class Dog { public:    ~Dog() {  cout << "Dog is destroyed"; } }; class Yellowdog : public Dog { public:    ~Yellowdog() {cout << "Yellow dog destroyed." < }; class DogFactory { public:     //static Dog* createYellowDog() { return (new Yellowdog()); }    static shared_ptr createYellowDog() {        return shared_ptr (new Yellowdog());     }     //Connot  useful through Unique_ptr in this case //static unique_ptr createYellowDog() {    //   return unique_ptr (new Yellowdog());    //} }; in...

Sequence Containers: Array

Arrays are fixed-size sequence containers: they hold a specific number of elements ordered in a strict linear sequence. They cannot be expanded or contracted dynamically Another unique feature of array containers is that they can be treated as  tuple  objects Container properties Sequence Contiguous storage (allowing constant time random access to elements) Fixed-size aggregate Example: #include #include int main () {   std::array myarray = { 2, 16, 77, 34, 50 };   std::cout << "myarray contains:";   for ( auto it = myarray.begin(); it != myarray.end(); ++it )     std::cout << ' ' << *it;   std::cout << '\n';   return 0; }

Disallow the use of compiler generated functions

/* C++ 11 Update: Delete keyword */ class dog {    public:    dog(const dog& ) = delete; // Prevent copy constructor from being used.                               // Useful when dog holds unsharable resource. } /* For C++ 03: Solution:  Declare them as private functions, but not define them.  -- Members and friends get link-time error, others get compile-time error. */ class dog {    private:    dog& operator=(const dog& rhs);    }; // Note: the same techniques can used to disallow any function from being used. Question: Can we disallow destructor from being used?  /* Solution */ class dog {   public:      void destroyMe() { delete this; }      void dog(string message) { cout<   private:      ~dog() { cout<< m_name.m_str ...

Default keyword in C++

class collar { public: collar() { std::cout <<  " collar is born.\n"; }  //Since collar in dog class invokes default constructor in collar }; class dog { collar m_collar; string& m_name;    // Reference should be initialized, hence leads to an error. }; int main() { dog dog1; } output: main.cc:13: error: no matching function for call to `dog::dog()' main.cc:8: note: candidates are: dog::dog(const dog&) // Add to dog: // string& m_name;  // Result: not compilable because age is not initialized. /* C++ 11 Update: */ class dog {    public:       dog() = default;       dog(string name) {...}; }

const used with functions

const used with functions : class Dog {    int age;    string name; public:    Dog() { age = 3; name = "dummy"; }         // const parameters and these are overloaded functions    void setAge(const int& a) { age = a; }    void setAge(int& a) { age = a; }         // Const return value    const string& getName() {return name;}         // const function and these are overloaded functions    void printDogName() const { cout << name << "const" << endl; }  // value of name can't be modified    void printDogName() { cout << getName() << " non-const" << endl; } }; int main() {    Dog d;    d.printDogName();        const Dog d2;    d2.printDogName();     }

POST 1 : std::thread in c++ | C++ 11

std::thread   C++  Thread support library std::thread. Threads enable programs to execute across several processor cores. Defined in header Class : thread Member types : native_handle_type Data Member  id    //represents the id of a thread (public member class) Member functions (constructor)    //constructs new thread object (public member function) (destructor)    //destructs the thread object, underlying thread must be joined or detached  (public member function) operator=    //moves the thread object  Observers  // Covered in NEXT POST Operations    // Covered in NEXT POST Constructor :   #include   void f1 ( int n ) { for ( int i = 0 ; i < 5 ; ++ i ) { std:: cout << "Thread 1 executing \n " ; ++ n ; std:: this_thread :: sleep_for ( std:: chrono :: milliseconds ( 10 ) ) ; ...