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.





Why the downvotes? It's a perfectly fair question, IMHO.
– Silvio Mayolo
Aug 22 at 1:38





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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế