-1
#include <iostream>
using namespace std;
class students {
        public:
                students(); //default constructor
                students(const students & s1); //copy constructor 
                void setScore(double p) { score = p; } //score setter
                students operator+(const students & s2) const; //define students + students
        private:
                double score; //the score variable
};

int main() {
        cout << "omidh object ";
        students omidh;
        cout << "negin object ";
        students negin;
        negin.setScore(2.0);
        omidh.setScore(3.0);
        cout << "total object ";
        students total = omidh + negin;
}

students students::operator+(const students & s2) const {
        cout << "s3 object ";
        students s3;
        s3.score = score + s2.score;
        return s3;
}

students::students() {
        cout << " used default constructor\n";
}

students::students(const students & s1) {
        cout << " used copy constructor\n";
}

Here is a simple class, the objects "omidh", "negin" and "s3" invoked default constructor but I don't know what constructor does "total" invokes. It supposed to invoke a copy constructor because I returned a student object as the return type for operator overload. However it works fine and assigned s3 to total.

Program outputs:

omidh object used default constructor

negin object used default constructor

total object s3 object used default constructor

omidh
  • 2,526
  • 2
  • 20
  • 37
  • see http://stackoverflow.com/questions/1758142/why-copy-constructor-is-not-called-in-this-case – fghj May 23 '15 at 16:38

1 Answers1

2

Due to return value optimization, total and s3 are the same object.

Edit: this is actually RVO, not copy elision

StenSoft
  • 9,369
  • 25
  • 30
  • Worth mentioning that (in g++/clang++) compiling with `-fno-elide-constructors` disables copy elision and allows one to see all constructors in all their glory. – vsoftco May 23 '15 at 16:37