Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compiler generated constructors [duplicate]

This is just a quick question to understand correctly what happens when you create a class with a constructor like this:

class A
{
  public:
    A() {}
};

I know that no default constructor is generated since it is already defined but are copy and assignment constructors generated by the compiler or in other words do i need to declare a private copy constructor and a private assignment operator in order to prevent this from happening?

class A
{
  private:
    // needed to prevent automatic generation?
    A( const A& );
    A& operator=( const A& );
  public:
    A() {}
};
like image 407
codencandy Avatar asked Mar 04 '10 16:03

codencandy


2 Answers

Yes, copy constructor and copy assignment operators are still created even if you declare your own default constructor.

The creation of those are only suppressed if you declare your own copy constructor or copy assignment operator in the class definition respectively.

Note that it is possible to have both your own copy constructor, and a compiler provided one:

struct A {
  A() { }
  A(A const&, int foo); 
}; // compiler declares a copy constructor now

// make the second parameter have a default argument
// now this constructor is a copy constructor too. 
inline A::A(A const&, int foo = 0) {

}

int main() {
  A a;
  A b = a; // ambiguity between compiler's one and our custom one!
}

The Standard however allows compilers to accept this code - but the effect is similar to having undefined behavior: The program is ill-formed, but no warning/error is required for that program. (early GCC versions don't reject this code, recent ones reject it).

like image 102
Johannes Schaub - litb Avatar answered Oct 11 '22 03:10

Johannes Schaub - litb


Yes. The copy constructor, assignment operator, and destructor are always created regardless of other constructors and operators.

If you want to disable one, what you've got there is perfect. It's quite common too.

like image 29
GManNickG Avatar answered Oct 11 '22 02:10

GManNickG