0
Can i initialize variables with value when we creatjng class??
Example: Class temp{ Private: Int a[3] = {12,2,3}; };
8 odpowiedzi
+ 3
In any of these cases, in case of doubt, you should do this:
Just try it.
Make a little code, testing if what you want to do works.
#include <iostream>
using namespace std;
class C{
int a[3] = {12,2,3};
public:
void f() {
cout << a[0] << a[1] << a[2] << endl;
}
};
int main() {
C x = C();
C y = C();
x.f();
y.f();
return 0;
}
+ 2
I think you can but the 'i' of int must be small 😅
+ 2
You may find answer in https://www.quora.com/Why-cant-we-initialize-the-value-for-a-variable-inside-a-class-C%2B%2B?ch=10&share=b032448c&srid=5rAgu and You may go through https://www.bestprog.net/en/2018/09/14/initialize-variables-in-class-methods-initialization-of-fields-data-members-of-the-class-ways-to-initialize-data-members-of-the-class/.
+ 1
Do you mean values for each instance? Or static class variables? Or something else?
Can you explain with more detail, what exactly you want to do?
+ 1
For each instances
+ 1
If i create object of temp t then t has a[3] variable with values 12,2 and 3.
Is it right to do?
+ 1
It can be done. That's part of what constructors are for. You can have default values for some fields.