Sololearn: Learn to Code
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1
Construtors are very useful in OOP.. You can't see the difference between the two example given above..but declare “int age" as private data member and then run the program..you will get an error..because objects can not access private data members..So you will create another public function to initialize variable and will call it using object..which increases length of code so construtors are used for initializing data members without the need of another function.. It has many more uses but this is most used i guess..
5th Sep 2019, 9:31 AM
Alaska
Alaska - avatar
+ 3
Object Oriented Programming (OOP) should have constructor even though you can do it without them. Based on your code provided, it is a small program, you can't see any use of constructor. For the heavy project, you will need the constructor to create the objects. The "proper way" is to use the first option. You can see this, https://stackoverflow.com/questions/13773710/can-a-class-have-no-constructor
5th Sep 2019, 2:32 AM
Uchiha Itachi
Uchiha Itachi - avatar
+ 2
In my opinion, Second option doesn't recommended but doesn't mean cannot use. To code properly, the first one in suggested.
5th Sep 2019, 2:24 AM
Uchiha Itachi
Uchiha Itachi - avatar
+ 2
I believe that in the second case, a default constructor is used, allocating memory to all the fields etc. although initialising the age field to 15 is not done in the constructor.
5th Sep 2019, 3:04 AM
Sonic
Sonic - avatar
+ 1
No..you are a bit wrong here..“To INITIALIZE private member of created instance" See whenever you create an object/instance a new memory space is created which stores value of data members.. For example. Class abc { int a; Public: void abc() { cin>>a; } }; Now lets create two objects..a1,a2.. Now both the times construtor will be called and will ask user for value..lets say 10 and 20..so object a1 will have value 10 and a2 will have value 20.. In your case, both the objects will acquire default value 15..but remember that they will not point to same memory location ..(Try printing memory locations of both...) My point is objects do not share same data members i.e a will be different for a1 and a2 but the function or static members which you will define will be shared ..
6th Sep 2019, 2:36 AM
Alaska
Alaska - avatar