+ 1

Parametric constructor with istream object

Hi Refer code below. It works okay with default constructor. If I remove that one, obviously it will throw error. Can I make this work without default constructor? In other words, can I have parametric constructor works without default constructor? https://sololearn.com/compiler-playground/cqmGZ1z3VC6e/?ref=app

3rd Nov 2024, 6:17 PM
Ketan Lalcheta
Ketan Lalcheta - avatar
7 Réponses
+ 2
It is requiring the default constructor because you are creating an object without parameters. obj2. If you only want to use the parametric constructor, then you must include the constructor parameters to instantiate the object. That's my best understanding of your code after a quick review.
3rd Nov 2024, 10:19 PM
Jerry Hobby
Jerry Hobby - avatar
+ 2
have you tried providing default values to the constructor parameters? currency(int r=0, int p=0):rs(r),paise(p){} This is what your default constructor is essentially doing anyway. if you don't really private properties, structs are simpler because you don't need friend priviledge for ostream https://sololearn.com/compiler-playground/c07GI4labF8p/?ref=app
3rd Nov 2024, 10:25 PM
Bob_Li
Bob_Li - avatar
+ 1
Not that I know of. The question I want to ask is what particular situation would a class not be allowed to define a default constructor when the use case clearly demands it? Instantiating directly through cin sounds sketchy, if it is posible at all. One workaround is to collect the user inputs, then use a factory function to initialize the instance. This way, you don't have to use default constructor, just the parameterized one. Here is a similar question I found: https://cplusplus.com/forum/beginner/117088/
4th Nov 2024, 9:03 AM
Bob_Li
Bob_Li - avatar
+ 1
Ketan Lalcheta not directly passing the constructor to cin, but using a factory function which uses cin to provide the arguments to instantiate and create unique_ptr for currency. https://sololearn.com/compiler-playground/c6iB0bZ9I9o4/?ref=app
4th Nov 2024, 10:59 AM
Bob_Li
Bob_Li - avatar
0
Default argument to parametric constructor or default constructor is something I don't want. In other words, I need user not to create dummy object without properties. In such case, how to have istream create object with proper property values
4th Nov 2024, 8:09 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
0
Ketan Lalcheta without a default constructor or a default value parametric constructor, line 40 currency obj2; will raise an error. You will be unable instantiate obj2 this way. You don't even get to line 41 where you pass obj2 to cin. cin >> obj2;
4th Nov 2024, 8:26 AM
Bob_Li
Bob_Li - avatar
0
Yeah, that's what I wanted to ensure. Is there anyway I get istream operator overloaded to have fully constructed object as return value or by reference. I belive no way. Right?
4th Nov 2024, 8:33 AM
Ketan Lalcheta
Ketan Lalcheta - avatar