+ 1
In public section- is 'var' acting as a data type for (a) during initialization. Or is (a) being assigned to variable 'var'.
class MyClass { public: MyClass(int a) : var(a) { } private: int var; };
3 Respostas
+ 1
It looks like you trying to use a Constructor Initialization List.
The argument a is passed to the constructor and var(a) assigns the argument a to the variable var. If you have more than 1 you can comma separate them.
See code here:
https://goo.gl/37dOqi
or here in the code playground:
https://code.sololearn.com/c8Ad35RlKEvg
+ 1
#include <iostream>
using namespace std;
class MyClass {
public:
// Contructor Initialization Lists Example
MyClass(int a): var(a), hi("Hello") {}
int getVar(){
return var;
}
string sayHello(){
return hi;
}
here's that code and in public section there is this "hi" . Is that a variable too.. how can it have no d
ata type?
MyClass c(10);
int a = c.getVar();
cout << a << endl << c.sayHello() << endl;
return 0;
}
0
It has a data type of string and is declared just below the int var in the private section of MyClass. Take another look. You don't have all the code there.