does default copy constructor handle const?

1.6k views Asked by At

I learned that default copy assignment operator (EDIT: corrected, not copy constructor) doesn't handle const and reference. Hence, if a class contains such members, then the compiler will not generate default copy constructor for it. Is this statement correct? Why const can not be handled?

Besides, if a class contains pointers as members, will the compiler generate a copy constructor? I understand default copy constructor only does shallow copy, but the compiler will at least generate a copy constructor, will it?

Thanks a lot for clarification!

2

There are 2 answers

3
Kerrek SB On

If you do not define a copy constructor for a class X, a copy constructor is implicitly defined. It usually takes the form X(const X&), but it may also be have one of the other one-parameter forms if members require it, and it may be defined as deleted. The constructor behaves as if each member were initialized from the corresponding member of the right-hand side, and has an empty body. There are details, but that's the general idea.

Since you can initialize const data members and reference data members from values of the same type, there is nothing special about such members. (The story is different for assignment, though.)

0
Vlad from Moscow On

A constructor needs a means to initialize constant non-static data members and non-static data members of reference types because these data members shall be initialized when the corresponding object is created. So either you have to write the default constructor yourself or these data members must have brace-or equalt initializers specified in the class definition.

Also some data members can have no default constructors. So the compiler is unable to create the default constructor for the class because it can not call corresponding default constructors of such data members.

As for pointers then they do not prevent the compiler to define the copy constructor.

Here is a demonstrative program

#include <iostream>

struct A
{
    const int i = 10; 
};

struct B
{
    const int i; 
};

int main()
{
    A a;
    std::cout << "a.i = " << a.i << std::endl;

//  B b; // compilation error
}    

For structure A the compiler defined implicitly the default constructor because data member i is initialized in the class definition. However for structure B the compiler is unable to define the default constructor because it does not know how to initialize constant data member i.