-2

The code is :

#include <iostream>
using namespace std;

class Point
{
    int x, y;
 public:
    Point(const Point &p) { x = p.x; y = p.y; }
};

int main()
{
    Point p1; // COMPILER ERROR
    Point p2 = p1;
    return 0;
}

The above code throws an error: COMPILER ERROR: no matching function for call to 'Point::Point()

Compiler does not create a default constructor, when we create our own copy constructor. Why?
Is this just a C++ standard rule or Is there some reason ??

EDIT: I am aware of the rule. I am just looking for the reason.

Krishna Kanth Yenumula
  • 2,533
  • 2
  • 14
  • 26
  • https://stackoverflow.com/questions/563221/is-there-an-implicit-default-constructor-in-c – Retired Ninja May 23 '21 at 07:05
  • A class type (`struct`, `class` or `union`) is mostly meaningless if its instance can not be created. Hence the compiler provides a default constructor if it does not find one. If you create a constructor, there is a way to create an object. So the compiler does nothing in such a case. – Kitswas May 23 '21 at 07:17
  • Please provide reason for downvote. I know the rule. I am looking for the reason, why default constructor is not provided. – Krishna Kanth Yenumula May 23 '21 at 07:17
  • Copying your objects requires special logic (as far as the compiler can tell, since you provided some hand-made implementation). It's no different than if you provided some other parameterized constructor, you do something special. So the compiler shouldn't assume it can just generate the default c'tor for you. It doesn't *know* what you need, and its implementation can be entirely unreasonable for your needs. So it doesn't provide one (unless **explicitly** requested). – StoryTeller - Unslander Monica May 23 '21 at 07:56

1 Answers1

4

The rule is that if any constructor doesn't exist, a default constructor is automatically made. From cppreference:

Implicitly-declared default constructor

If no user-declared constructors of any kind are provided for a class type (struct, class, or union), the compiler will always declare a default constructor as an inline public member of its class.

Since there is one user-declared constructor (the copy constructor), no default constructor is provided.

mediocrevegetable1
  • 4,086
  • 1
  • 11
  • 33