Home > Software design >  How do I use a class variable inside of that class? (C )
How do I use a class variable inside of that class? (C )

Time:02-05

This is the code I'm trying to run:

class poly {
    public:
        int vnum;
        vrtx vrts[this->vnum];
};

(Note: The class name "poly" and other class "vrtx" are named as such to approximate the purpose of the problematic snippet. Vrtx is a class with int x, y, z;)

At first, the code didn't contain the "this->" pointer at all. I was confused why it wasn't working, and then realized that "vnum" doesn't mean anything. I needed an object.poly.vnum sort of thing so that I'm referencing a specific value. I tried "this.," "this.poly.," and the displayed "this->," but none of them work. I'm not great with pointers, so any advice would be appreciated!

I've looked at similar questions, but none of them address this issue in such a way that I could make the necessary fix with the information provided.

CodePudding user response:

Here's a code fragment that should help.

class Poly
{
  public:
    int vnum;
    std::vector<vrtx> vrts;
    Poly(int capacity)
        : vnum(capacity)
        { vrts.resize(vnum);}
};

The above fragment uses std::vector since the std::vector can expand dynamically (at run-time). The constructor uses the resize method to expand the std::vector to the given capacity.

Arrays are a pain to resize during run-time, so use std::vector.

  • Related