Skip to main content

Posts

Showing posts from January, 2018

Sequence Containers: Vectors

Vectors are sequence containers representing arrays that can change in size. Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container. Container properties Sequence Dynamic array Allocator-aware Example : #include #include int main () { std::vector< int > myvector; for ( int i=1; i<=5; i++) myvector.push_back(i); std::cout << "myvector contains:" ; for (std::vector< int >::iterator it = myvector.begin() ; it != myvector.end(); ++it) std::cout << ' ' << *it; std::cout << '\n' ; return 0; }

Clone Function in C++

class Dog {  public:    virtual Dog* clone() { return (new Dog(*this)); }  // co-variant return type }; class Yellowdog : public Dog {     virtual Yellowdog* clone() { return (new Yellowdog(*this)); } }; void foo(Dog* d) {      // d is a Yellowdog    //Dog* c = new Dog(*d); // c is a Dog    Dog* c = d->clone();    // c is a Yellowdog     //...     //  } int main() {    Yellowdog d;    foo(&d); }

Invoke Virtual Function in Constructor or Destructor

Case 1:  class Dog { public: Dog()  { cout << "Dog Born" << endl; } virtual void bark()  { cout << "Dog barking" << endl; } void SeeCat() { bark();  // first it check bark() in YellowDog else invokes in Dog class } }; class YellowDog : public Dog  { public: YellowDog() { cout << "Yellow Dog Born" << endl; } virtual void bark()  // virtual keyword is optional        { cout << "Yellow barking" << endl; } }; int main() { YellowDog d; d.SeeCat(); } Output:  Dog Born Yellow Dog Born Yellow Dog barking Case 2: why Virtual function in constructor  should be avoided class Dog { public: Dog()  { cout << "Dog Born" << endl; bark();  Since construtor of yellowdog is not yet constructed, so bark of Dog class gets called. } virtual void bark()  { cout << "Do...

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