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];
}
22
  • What are your compiler flags? The copy might be optimized away Apr 30, 2014 at 7:20
  • this code is fine, I've tried it and it prints hello.
    – Shikamu
    Apr 30, 2014 at 7:22
  • works fine with gcc 4.8.1
    – Kiroxas
    Apr 30, 2014 at 7:25
  • 3
    What output do you get, and what output do you expect? Apr 30, 2014 at 7:57
  • 1
    @KeillRandor There is no assignment in his example, so overriding the assignment operator will have no effect. (Of course, for any real use, he should either override it or ban it.) Apr 30, 2014 at 8:27

1 Answer 1

2

You code is working as expected. See here.

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

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.