Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing class to constructor, when no such constructor exists. Why does it work? [duplicate]

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?

like image 253
Zartock Avatar asked May 10 '19 15:05

Zartock


People also ask

What happens if there is no copy constructor?

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.

How many times is copy constructor called?

You call the function by value and do two copies inside.

Can a class have no copy constructor?

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.

What is true about copy constructors?

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.


1 Answers

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.
like image 117
Maxim Egorushkin Avatar answered Oct 26 '22 14:10

Maxim Egorushkin