-1

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

aaliyah
  • 19
  • 3
  • 1
    Almost certainly it any difference is optimized away by the compiler, if you enable optimizations, but try the same with a member of type [`std::lock_guard`](https://en.cppreference.com/w/cpp/thread/lock_guard/lock_guard) and you cannot use the second version. Therefore prefer the first version, since it always works and doesn't run the risk of running a possibly expensive additional member variable constructor+assignment operator... – fabian Aug 11 '23 at 16:26

0 Answers0