Valid to set an object equal to the constructor of same class in c++?
Valid to set an object equal to the constructor of same class in c++?
The code is as follows:
class A
public:
A();
;
class B
public:
B()
a=A();
private:
A a;
;
It compiles alright but I am not sure if it is correct and in what purpose it serves. I believe that the code sets 'a' equal to the value in the default constructor, but that is what 'a' is already equal too when the object was created.
First and foremost
=
does not mean set to equal, it means assign value (or initialize depends on context). It is perfectly fine to assign the same value to the same variable (though pointless in this case)– Slava
Aug 22 at 1:56
=
Not "the value in the default constructor" but "a default-constructed object". It is the same as
A b; a = b;
.– molbdnilo
Aug 22 at 7:28
A b; a = b;
1 Answer
1
Valid? Completely. Pointless? Probably. You're right that an extra object is getting made there. We can verify this by having the A
default constructor display something.
A
class A
public:
A() printf("Made an A!n");
;
This will print "Made an A!" twice, confirming your hypothesis.
If I had to guess, I'd say this code was written by someone who comes from Java, where instance variables are initialized to null
, rather than automatically calling the default constructor. Code like this is not idiomatic C++, and if I saw it in a code review I should think it would raise eyebrows. Either construct the object explicitly with B() : a()
or simply let it default construct by not mentioning it at all, as you suggest.
null
B() : a()
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Why the downvotes? It's a perfectly fair question, IMHO.
– Silvio Mayolo
Aug 22 at 1:38