user6646922
user6646922

Reputation: 517

Are int a = 5 and int a(5) equivalent in C++?

Both int a = 5 and int a(5) yield the same output when displayed on stdout. Also int* b = new int and int* b(new int) seem to be the same. Are those just two different ways to initialize a variable and declare a pointer or is there a bigger picture? Frankly I had no idea you could initialize a primitive data type with no assignment operator.

Upvotes: 1

Views: 3333

Answers (1)

Pete Becker
Pete Becker

Reputation: 76438

Yes, they're the same.

On the other hand, for a class type they're subtly different.

struct S {
    S(int);
    S(const S&);
};

S s(5);   // 1
S ss = 5; // 2

The line marked 1 uses S(int) to construct s. The line marked 2 is a bit more complicated. Formally, it uses S(int) to construct a temporary object of type S, then uses S(const S&) to copy that temporary into ss.

However, the compiler is allowed to skip the copy, and construct ss directly, with S(int), and in practice, every compiler does this. But the copy constructor still has to exist and be accessible; only its use is elided. So if S(const S&) was marked private, the line marked 2 would be ill-formed. You can try this out by writing a copy constructor that writes something to std::cout to tell you when it's called; the compiler is allowed to skip that call, even though it has visible side effects.

Upvotes: 2

Related Questions