0

I was writing a simple program to show different types of constructors available in C++(default, parametrized, and copy). When I encountered this problem(if that's right to say it a problem). What I'm posting here isn't the actual program but it is a part of the main program.
Code:

#include <iostream>
using namespace std;

class A
{
        public:
                A (A&)
                {
                        cout << "copy ctor of A.\n";
                }
                ~A ()
                {
                        cout << "dtor of A\n";
                }
};

int main()
{
        A obj(obj);
        return 0;
}


So my question here is:

  1. What means A obj(obj); here?
  2. How copy constructor is taking reference to an object which even doesn't exist in the memory?
Shubham
  • 1,153
  • 8
  • 20
  • `A obj(obj);` has the same meaning as `A obj = obj;`. Something the language still allows, but is almost certainly a typo. – Drew Dormann Apr 04 '21 at 18:33
  • @DrewDormann But how is it working? – Shubham Apr 04 '21 at 18:36
  • @DrewDormann I got the answer to Q1. What about Q2? – Shubham Apr 04 '21 at 19:04
  • Consider that, inside your constructor, `this` represents a pointer to an object that has not yet been constructed. It is a pointer to an object that, in your words, "even doesn't exist". The `A&` passed to the constructor is a reference to that same memory. – Drew Dormann Apr 04 '21 at 19:06

0 Answers0