Implicitly defined members of a class in C++

What members of a class are implicitly defined?

There are quite a few things that you get when you make a class (if they aren't explicitly defined). The important thing to note is that they are not actually created/written by the compiler unless it's sure that you need them. Let's go ahead with an example empty class named 'MyClass'. Below are those members alongwith the constructs that force them into existence:
  • Default (zero-argument) constructor
    Whenever an object of the class is created unless there are any parameterized constructors defined.

    MyClass ObjectOfMyClass;   // Object creation
  • Copy constructor
    Whenever copy construction is initiated.

    MyClass ObjectOfMyClass;
    MyClass AnotherObjectOfMyClass = ObjectOfMyClass;   // Copy construction
  • Assignment operator
    Whenever the assignment operator '=' is used with objects of the class.
    MyClass ObjectOfMyClass;
    MyClass AnotherObjectOfMyClass;
    // some more code manipulating the objects
    ObjectOfMyClass = AnotherObjectOfMyClass;   // Assignment  operator
  • Destructor
    If there is an explicitly/implicitly defined constructor (nothing to do with the keyword 'explicit') and an object is created. That would mean if you went through some code as stated in the first point, a destructor would be generated and called whenever the object is destroyed. 


  • A pair of 'address-of' operators
    There are two versions: a 'const' one and a 'non-const' one. When the '&' ('address-of') operator is used on a const object, first version is generated and the later one associates itself with a non-const object with similar usage.

    MyClass ObjectOfMyClass;
    const MyClass ConstObjectOfMyClass;
    MyClass* ptr = &ObjectOfMyClass;   // Causes non-const version creation
    ptr = &ConstObjectOfMyClass;   // Causes const version creation
If there are all the above mentioned operations in a program, the empty 'MyClass' would be somewhat equivalent to:
class MyClass
{
  public:
    MyClass() {}
    MyClass(const MyClass& rhs) {}
    MyClass& operator=(const MyClass& rhs) {}
    MyClass* operator&() { return this; }
    const MyClass* operator&() const { return this; }
    ~MyClass() {}
};
These will appear in all cases where you don't explicitly define them but are forcing their calls in the above mentioned ways. So just be aware.
Note : If you define the copy constructor for your class, you don't get the default constructor.

Source:
http://www.codeguru.com/forum/showthread.php?t=356418

0 comments:

Post a Comment