0
#include<iostream>
using namespace std;

class A {
  int k;
  int *ptr;
public:
  A(int a):k(a) { 
    cout<<"ctor\n";
    ptr = new int[k];
    for(int i = 0; i < k; i++) {
      *(ptr + i) = i*i*i;
    }
  }
  A(const A &obj) {
    cout<<"copy ctor\n";
    k == obj.k;
    ptr = new int[k];
    for(int i = 0; i < k; i++) {
      *(ptr + i) = i*i;
    }
  } 
  void show() {
    for(int i = 0; i < k; i++) {
      cout<<*ptr++<<" ";
    }
  }
};

A foo() {
  A temp(5);
  return temp;
}

int main() {
  A obj = foo();
  obj.show();
  return 0;
}

** The temp object returned by foo() is not copied. Normal constructor is called in this but not copy constructor. Can anyone point where exactly I am going wrong.**

Jarod42
  • 203,559
  • 14
  • 181
  • 302
Sadik Khan
  • 29
  • 3
  • 2
    Look at copy elision. – Jarod42 May 24 '17 at 11:51
  • 2
    Warning: You have violated the Rule Of Three! – aschepler May 24 '17 at 11:51
  • 1
    Your copy-constructor doesn't copy the contents of `obj.ptr`, it merely set the contents to something other. – Some programmer dude May 24 '17 at 11:51
  • 1
    Also, your `show` function is *very* flawed. Where will `ptr` point after you called the function? – Some programmer dude May 24 '17 at 11:52
  • 1
    ``k == obj.k;`` pretty sure you meant ``k = obj.k``. BTW use the initialisation list for the constructor. – nefas May 24 '17 at 11:55
  • yeah it's k = obj.k. For initialisation, it's working but on function return it's not working @nefas – Sadik Khan May 24 '17 at 12:01
  • I don't understand what you mean by "For initialisation, it's working but on function return it's not working". Sorry – nefas May 24 '17 at 12:03
  • Yes, the show function has flaw and I have corrected it. My question is, deep copy is performed on initialising(e.g. A obj2 = obj), But the function return is not performing any deep copy. – Sadik Khan May 24 '17 at 12:05
  • I mean if I am initializing any object say like this ( A obj2 = obj), the copy constructor is getting called. But if I I do something like this A obj = foo(), the it's not calling copy constructor @nefas – Sadik Khan May 24 '17 at 12:10
  • for that, check the link on top of the question: it has the answer. My comment is just a tip for writing better code (and fix a bug). – nefas May 24 '17 at 12:15
  • thanks @Jarod42 , it's the case of copy elision, I have disabled copy elision and now it's working – Sadik Khan May 24 '17 at 12:18
  • By disabling copy elision all you've really done is get rid of the symptom. You should make sure you understand the comment by @nefas regarding the [rule of three](http://en.cppreference.com/w/cpp/language/rule_of_three). – G.M. May 24 '17 at 12:32

0 Answers0