Search code examples
c++arraysclassglobal-variables

Unable to modify an array inside of a class in C++


I am new to C++. I just wrote this program in Visual Studio Code, but I am receiving two errors which I haven't found an explanation for.

This is the code:

#include <iostream>
using namespace std;
class net{
    public: bool isConv = false;
    public: int structure[2];
    structure[0] = 1;      
};
int main() {
    net n;
    cout<< n.structure;
    return 0;
}

The errors I am receiving are:

error: C++ requires a type specifier for all declarations" in line 5

error: duplicate member 'structure'" in line 6

I think the code believes I am trying to define a new variable called structure in line 6, when instead I am only trying to modify the first value of the array.

The same two lines of code work fine if they are in the main() function, but inside the class they seem to not be working.

Can anyone help me understand why I have these errors, and how to fix them?


Solution

  • In a class, you define all the variables and functions, but what you're trying to do is that you try to make an operation within the class. You can make them only inside functions, so the best way to solve your problem would be to make the operation inside the constructor of the class. Constructor is a function, which is named the same as the class, and which runs when you initialize a class.

    There are a few other problems, which don't necessarily make your code not work, but it is better to avoid them.

    The first is that you think of the public and private keywords as in for example Java, where you make a function or a variable private depending on what keyword preceeds them. In C++ classes, they work as something like "sections" and the function/variable is public/private depending on in which section you define them.

    Another problem is that you make everything public, although it's not necessary. If you want to access a variable, either to read it or modify it, you can always use a getter or a setter. Those are basically functions, that either return the variable (getters) or modify the variable (setters).

    If you want to make a function accessible (public) to the user of the class, you define it in the public "section" of the class, and if you want it to be private and be used only by the class itself, define it in the private "section".

    When you print just the structure array, you don't print the array's variables, but its memory address, because C-style arrays in C++ are just pointers. That is also why when returning a C-style array in C++, the return type has to be a pointer (so in your case int*, and not just int). If you want to print them all, make a for-loop and just loop through the array and print the variables. If you want to print for example just the first element, call the getter function and append [0] to it like you would do with a normal array. If you're not ready to learn pointers yet, as it can be pretty rough to learn them at the beginning, you can take a look at vectors.

    Last problem with your code is the line using namespace std;. It's not such a big deal when writing small programs or learning, but you should avoid it in the future.

    Also, class names are usually capitalized (at least from my experience).

    I included some comments in the code for you so you can better understand it. The code after eliminating all the problems (except for the using namespace std; problem, because I don't want to confuse you too much) should look like this:

    #include <iostream>
    
    using namespace std;
    
    class Net {                       // Capitalized class name
    public:                           // Public section of the class, define your public functions here
        Net() {                       // This is the constructor
            this->structure[0] = 1;   // "this->" means we are referring to a variable belonging to the class
        }
        int* get_structure() {        // A getter for the structure array
            return this->structure;   // Returning the array
        }
    
    private:                          // Private section of the class, define your variables and functions used only by the class here
        bool isConv = false;
        int structure[2];
    };
    
    int main() {
        Net n;
    
        int* structure = n.get_structure();   // Store n.structure in the structure variable (even though it is a pointer, you can use it as normal array)
    
        cout << n.get_structure() << endl;    // Output: (a memory address)
        cout << n.get_structure()[0] << endl; // Output: 1
        cout << structure << endl;            // Output: (a memory address)
        cout << structure[0] << endl;         // Output: 1
    
        return 0;
    }