I'm having a class that looks like:
class A {
public:
A(float v)
{
A::v = v;
}
float v;
float set(float v)
{
A::v = v;
return v;
}
float get(float v)
{
return A::v;
}
};
Then I instantiate 2 objects of class A:
A* a = new A(1.0);
A* b = new A(*a);
Why are there no errors when my Class A doesn't have a constructor which takes a class A?
Copy Constructor is called when an object is either passed by value, returned by value, or explicitly copied. If there is no copy constructor, c++ creates a default copy constructor which makes a shallow copy. If the object has no pointers to dynamically allocated memory then shallow copy will do.
You call the function by value and do two copies inside.
If no user-defined copy constructors are provided for a class type (struct, class, or union), the compiler will always declare a copy constructor as a non-explicit inline public member of its class.
A copy constructor is a member function that initializes an object using another object of the same class. In simple terms, a constructor which creates an object by initializing it with an object of the same class, which has been created previously is known as a copy constructor.
The compiler generates a copy constructor for you:
If no user-defined copy constructors are provided for a class type (struct, class, or union), the compiler will always declare a copy constructor as a non-explicit inline public member of its class.
You can make the copy constructor and assignment deleted and make the compiler not declare move assignment and constructor by declaring one of move constructor or assignment as deleted:
A(A&&) = delete; // Makes the class non-copyable and non-moveable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With