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
5 Respostas
+ 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;
}
+ 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.
+ 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.
0
yes,ur r8t @zen
I want to store the value form main func
passing object as a parameter
0
in this program this pointer is required .
its necessary or not. & why pass the value 42 to func setn() in constructor