0

Say I have a class with a public variable (bad practice, I know), and in the main function, I want to create 3 class objects, how could I assign different values to that class variable?, something like:

class C{
    public:
        int foo;
};

int main(){
    C co[3];
    co[0]->foo = 20;
    co[1]->foo = 40;
    co[2]->foo = 80;
}
  • Well, besides the syntax being wrong (use `.` instead of `->`) that's one possible solution. Or you could create three distinct variables instead, like `C c1, c2, c3;`. Oh and if you only have public members, I'd recommend you make it a `struct` instead of a `class`. – Some programmer dude Jul 10 '22 at 10:35
  • the syntax is obviously wrong (thats kinda why I asked), and my class do have private members, I excluded it from the example because it is not relevant to the question – Cheesewaffle Jul 10 '22 at 10:38
  • @Cheesewaffle Replace `co[0]->foo` with `co[0].foo` and so on for others. – Jason Jul 10 '22 at 10:43

1 Answers1

0

Since you have different value for each object, you need to initialize them one by one.

Fortunately there is a simple way to kind of do it in s single swoop without using individual assignments: Initialize them at definition.

Create a suitable constructor:

class C
{
    int foo;

public:
    C(int foo)
        : foo(foo)
    {
    }
};

Then you can initialize the array like any other array:

C co[3] = { 20, 40, 80 };
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • 1
    If `foo` remains `public`, there's no need for a constructor. (I'm not to saying there's no benefit in making members `private`...) – fabian Jul 10 '22 at 10:52