0

how to use the constructor to take input form user.....?? nt using default constructor..

is it constructor is used only pass the parameters to the constructor

8th Sep 2016, 11:27 AM
vikil lakkavatri
vikil lakkavatri - avatar
5 ответов
+ 3
http://code.sololearn.com/cTu97bbduZNJ #include <iostream> using namespace std; class MyClass { private: int n = 42; public: MyClass() { } MyClass(int n) { this->n = n; } void setn(int n) { this->n = n; } int getn(void) { return this->n; } }; int main() { int n; cin >> n; MyClass c(n); cout << "c.n: " << c.getn() << endl; MyClass *c2 = new MyClass(n); cout << "c2->n: " << c2->getn() << endl; delete c2; return 0; }
8th Sep 2016, 12:25 PM
Zen
Zen - avatar
+ 2
You are able to overload your default contructor with arguements, just like you would do with a function. Except in this case it would execute when you create an object with the corresponding arguements, or manually call the constructor.
8th Sep 2016, 11:54 AM
Cohen Creber
Cohen Creber - avatar
+ 2
I like to use this->n whenever possible so that you can always see right away that n is an attribute of the class.
8th Sep 2016, 12:30 PM
Zen
Zen - avatar
0
yes,ur r8t @zen I want to store the value form main func passing object as a parameter
8th Sep 2016, 12:01 PM
vikil lakkavatri
vikil lakkavatri - avatar
0
in this program this pointer is required . its necessary or not. & why pass the value 42 to func setn() in constructor
8th Sep 2016, 12:12 PM
vikil lakkavatri
vikil lakkavatri - avatar