Looking at different ways to use constructors, and stumbled upon this one (the only difference between the two code segments are the constructors):
#include <iostream>
class Something {
private:
int attr1 {};
int attr2 {};
public:
Something(int Attr1, int Attr2): attr1{Attr1}, attr2{Attr2} {
//empty
}
int getAttr1() {return attr1;}
//Some other methods
};
int main() {
Something thing1(40, 34);
std::cout << thing1.getAttr1() << std::endl;
return 0;
}
how is that constructor different from this one?
#include <iostream>
class Something {
private:
int attr1 {};
int attr2 {};
public:
Something(int Attr1, int Attr2) {
attr1 = Attr1;
attr2 = Attr2;
}
int getAttr1() {return attr1;}
//Some other methods
};
int main() {
Something thing1(40, 34);
std::cout << thing1.getAttr1() << std::endl;
return 0;
}
the programs do exactly the same thing.
Which one do you prefer? Why? Which one is more efficient/better practice? Why?
Thanks!
The results are the same, so I wondered why there are different ways to do it, and when I am supposed to use which one