0

I have the following class:

class Fraction {
    private:
        int x;
        int y;
    public:
    // Constructors
        Fraction(long x = 0, long y = 1);
        Fraction(const Fraction&)=default;//here is the problem
        virtual ~Fraction();
 };

I'm trying to disable default C++ constructor to implement my own (I intend to use it for copy). So, I declared it as a default. But, when I'm trying to implement it:

Fraction::Fraction(const Fraction&){}

Compiler throws the following error at me:

./src/Fraction.cpp:16:1: error: definition of explicitly-defaulted ‘Fraction::Fraction(const Fraction&)’ Fraction::Fraction(const Fraction&){ ^ In file included from ../src/Fraction.cpp:8:0: ../src/Fraction.h:22:2: error: ‘Fraction::Fraction(const Fraction&)’ explicitly defaulted here Fraction(const Fraction&)=default;

Is there any way to fix it? What I'm doing wrong ? I found some articles about defaults, but nothing that can help me fix these errors.

AOquaish
  • 53
  • 1
  • 3
  • 8
Ophelia
  • 549
  • 1
  • 5
  • 26
  • If you want to disable the copy constructor, use `= delete`, not `= default`. – Jonathan Potter Jul 02 '15 at 05:11
  • 5
    `= default` tells the compiler to use the default implementation. This also means that __you cannot provide your own__. If you _don't_ want the compiler to create one, simply remove `= default`. – Zeta Jul 02 '15 at 05:12
  • 1
    *Default constructor* and *copy constructor* are two different things. – dlask Jul 02 '15 at 05:14

1 Answers1

7

= default tells the compiler to use the default implementation. This also means that you cannot provide your own. If you don't want the compiler to create one, simply remove = default:

class Fraction {
// ...
    Fraction(const Fraction&); // NO =default
};

By the way, the "default constructor" is the one that's called when you don't provide any arguments, e.g.

Fraction my_frac; // default constructor called

If you want to disable the default constructor, use =delete:

class Fraction{
public:
    Fraction() = delete;
}

Keep in mind that your current Fraction(long, long) provides default arguments, so it's eligible as a default constructor.

Zeta
  • 103,620
  • 13
  • 194
  • 236
  • But why we have to say to compiler to use default implementation? would it use the default one...by default? – Ophelia Jul 02 '15 at 05:16
  • 2
    @Ophelia: That's depends on the context. For example, if you provide your own constructor, it won't generate a default constructor anymore. If you still want to have one, you can simply use `= default`. [This answer](http://stackoverflow.com/a/20829116/1139697) provides some insights. – Zeta Jul 02 '15 at 05:19