Sunday, December 11, 2011

member functions are given by compiler in c++

Following member functions are given by compiler if we are not defined in the class..

1) default constructor
2) default destructor
3) copy constructor
4) assignment operator
5) address operator



Wednesday, November 23, 2011

Things to be taken care of in defination of assignment operator

  • Deep copy/shallow copy
  • Guard against self assignment in the assignment operator.
  • Strong exception safety in the assignment operator. (acquire new resources before deleting old)
  • Call base class's assignment operator if needed.

Final Class in C++

A class in Java is said to be final class if it can't be inherited by any other class. In C++, language has no built in feature to implement this. This has to be implemented by the developer.
  • By making the destructor private 
    • In this case, the object can only be created in heap by some static function defined in the class. Similarly a function must be implemented for destruction of object.
    • If we create object on stack, stack unwinding needs the destructor to be accessible. Hence compiler won't allow this.
    • Let's look at the following code.
    •  
    • Here no class can inherit F as the destructor is private. During child class object destruction, parent class destructor can't be called. Because parent class destructor is private.

  • By friend class
    • In this case, the object can be created on stack. 
    • Here we will need a dummy class whose destructor is private. The Final class must be a friend of this class and the Final class will inherit from dummy class.
    • We can create the object of Final class. As Final class is the friend of dummy class, it will have access to it's destructor. 
    • But if any class(Child) inherits Final Class, then it won't compile because destructor of temp is not accessible inside Child class.
    • Let's look at the following code