6

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?

Zartock
  • 63
  • 1
  • 3

3 Answers3

11

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.
Maxim Egorushkin
  • 119,842
  • 14
  • 147
  • 239
8

It does have the copy constructor: the compiler has generated one for you.

If you want to disable that explicitly, then write

A(const A&) = delete;

in the class declaration; and using

A(A&&) = delete;

deletes all the rule of five functions, except the destructor.

Bathsheba
  • 220,365
  • 33
  • 331
  • 451
5

An implicit copy constructor is generated by the Compiler, if you do not specify an own.

One further note:

Try

A a = 3.0f;

Conclusion: always mark constructors that take a single basic data type as explicit ... unless you like the implicit conversion

vlad_tepesch
  • 6,330
  • 1
  • 29
  • 67
  • 5
    "always mark constructors that take a single basic data type as explicit" ... unless you like the implicit conversion. – Brian Cain May 10 '19 at 15:09
  • 3
    That advice is out of date; you need to mark multi-argument constructors explicit too to obviate initialisation using `{}`. – Bathsheba May 10 '19 at 15:10
  • @Bathsheba I'd argue you're still less likely to want to `explicit` those, but it's possible – Lightness Races in Orbit May 10 '19 at 15:12
  • @BrianCain of course you are right. but in my expierence it is wanted rather seldom, maybe if you imeplement some number class that should behave transparently. – vlad_tepesch May 10 '19 at 20:03