As per cppreference documentation :
The implicitly-declared or defaulted copy constructor for class T is defined as deleted if any of the following conditions are true:
- T has non-static data members that cannot be copied (have deleted, inaccessible, or ambiguous copy constructors);
I am using a const
variable inside my Demo
class, so I am expecting that obj1
should not copy into obj2
because we have a const
variable, as shown in the below example:
#include <iostream>
using namespace std;
class Demo
{
public:
const int val = 100;//nonstatic data member that cannot be copied
Demo(){}
};
int main()
{
Demo obj1;
Demo obj2(obj1);
std::cout << "obj1.val :" << obj1.val << std::endl;
std::cout << "obj2.val :" << obj2.val << std::endl;
return 0;
}
Output:
obj1.val : 100
obj2.val : 100
Why is obj1
copied into obj2
? As per cppreference doc:
"implicitly declared copy constructor deleted if you have nonstatic data member which cannot be copied"