0

I am relative new to C++ and study copy-constructors. In this simple example I wanted to examine if really the copy-constructor that is explicitly defined is active. I put a cout-string there and I could not see that it's printed.

question: I wonder, why is the copy-constructor not used? Since in the main function body a copy of an object is made.

Person timmy_clone = timmy;

heres is the full code:

#include <iostream>

class Person {
public:
   int age;

   Person(int a) {
      this->age = a;
   }

   Person(const Person& person) {
      std::cout << "hello\n";
   }
};

int main() {
   Person timmy(10);
   Person sally(15);

   Person timmy_clone = timmy;
   std::cout << "timmy age " << timmy.age << " " << "sally age " << sally.age << " " <<   "timmy_clone age " << timmy_clone.age << std::endl;
   timmy.age = 23;
   std::cout << "timmy age " << timmy.age << " " << "sally age " << sally.age << " " << "timmy_clone age " << timmy_clone.age << std::endl;

   std::cout << &timmy << std::endl;
   std::cout << &timmy_clone << std::endl;

}

edit: I use MinGW and compile with -o

g++ main.cpp -o main.exe

edit2: here is another codesnippet where the explicitly defined copy-constructor is used. Still wonder why its used here and not in the first example?

   #include <iostream>

 class Array {
 public:
   int size;
   int* data;

  Array(int sz)
    : size(sz), data(new int[size]) {
  }
  Array(const Array& other)
     : size(other.size), data(other.data) {std::cout <<"hello\n";}

~Array()
{
    delete[] this->data;
}
 };


int main()
{
   Array first(20);
   first.data[0] = 25;

  {
    Array copy = first;
    std::cout << first.data[0] << " " << copy.data[0] << std::endl;
  }    // (1)

   first.data[0] = 10;    // (2)

  std::cout << "first data[0]: " << first.data[0];
}
user2991252
  • 760
  • 2
  • 11
  • 27

1 Answers1

2

You code is working as expected. See here.

Maybe you have confused with copy-elision which is not applicable here.

masoud
  • 53,199
  • 16
  • 130
  • 198