0

i have this block : Student s1; Student s2(s1); Student s3; Student s4 = s1; why is Student s4 = s1; going in the second constructor like Student s2(s1) ?

my code is this :

#include <iostream>
using namespace std;

class Date { int day, month, year;
   public:
       Date(int d=0, int m=0, int y=0)
           :day(d), month(m), year(y)
           {
               cout << " i am creating a date!" << endl;
           }
       Date( const Date& anotherd)
           : day(anotherd.day), month(anotherd.month), year(anotherd.year)
           {
               cout<< " i am creating a date by COPYING" << endl;
           }
};

class Student{
   Date registrationdate;
   public:
       Student(){
           cout << "i am creating a student" << endl;
       }
       Student(const Student& s){
           cout << "just copied" << endl;
       }
};


int main(){
   Student s1;
   Student s2(s1);
   Student s3;
   Student s4 = s1;
   cout <<"ok"<<endl;
   return 0;
   
}

Yakk - Adam Nevraumont
  • 262,606
  • 27
  • 330
  • 524
  • what do you mean by "equal"? – Wortig Jan 26 '21 at 12:36
  • @Wortig i changed it, i meant why is it going in the second constructor? – Θωμάς Κργ Jan 26 '21 at 12:38
  • not really sure but I think you are looking for that one: https://stackoverflow.com/questions/56501269/understanding-and-using-a-copy-assignment-constructor – yussuf Jan 26 '21 at 12:40
  • so in this example Student s4 = s1 is the same as Student s4(s1)? no difference? – Θωμάς Κργ Jan 26 '21 at 12:44
  • Yes, no difference. C++ is (in)famous for a billion ways to initialize things. Here `Student s4 = s1`, `Student s4(s1)` and `Student s4{s1}` are practically equivalent, though experts can perhaps assign to them different names. In short, to answer your question, `Student s4 = s1` needs to call some constructor of `s4` because it defines `s4`. The only reasonable candidate is the constructor that would be used in `Student s4(s1)`. – zkoza Jan 26 '21 at 13:00
  • You might also want to read this: https://stackoverflow.com/questions/49802012/different-ways-of-initializing-an-object-in-c/49802943 – zkoza Jan 26 '21 at 13:04
  • perfect, thank you so much – Θωμάς Κργ Jan 27 '21 at 14:02

0 Answers0