0

The question is pretty much in the title. Consider an empty class within the simple program, say

struct A{ };

int main(){ }

Does compiler have to instantiate all these functions anyway or it's implementation defined? I mean, intstatiate these functions in the case they are called only (I presume, compiler may determine if they are called somehow).

  • 1
    The special member functions are only implicitly-defined if they are odr-used. – David G Jun 04 '15 at 04:29
  • As far as the language standard goes, only templates are instantiated. "The compiler" has nothing to do with it. Being instantiated is a static property of a template, like being a member of a namespace or having a certain number of parameters. – n. m. could be an AI Jun 04 '15 at 04:51

2 Answers2

4

The special member functions are implicitly declared, unless they are odr-used, in which case they will be implicitly defined.

From N3337, §12/1 [special]

The default constructor (12.1), copy constructor and copy assignment operator (12.8), move constructor and move assignment operator (12.8), and destructor (12.4) are special member functions. [ Note: The implementation will implicitly declare these member functions for some class types when the program does not explicitly declare them. The implementation will implicitly define them if they are odr-used (3.2). See 12.1, 12.4 and 12.8. —end note ]

Praetorian
  • 106,671
  • 19
  • 240
  • 328
1

At the time of object creation, if compiler finds that there is no constructor defined for your class, it generates one for you. Constructors are functions that are required to initialize the data members of a class (and to perform other crucial operations such as setting up VTABLE and defining a VPTR - if your class declaration has atleast one virtual function).

At the time of a new object creation by copy constructor or copy-assignment operator (i.e, when creating an object from an existing object), the compiler-generated copy constructor would perform a mere shallow copy (plain bit-wise copy) of values of the data members (that could lead to a dangling-pointer situation - if your class has a pointer data member and you happen to create more than one reference/pointer to your class object, and then the object gets destroyed via one of those - due to some intentional/un-intentional reason, leading to a crash if you access those dangling pointer(s)). Hence its always advised to define your own copy constructor and copy assignment operator, and perform a 'deep copy' of your pointer whenever your class has a "pointer data member".

Mohammed Raqeeb
  • 75
  • 2
  • 12