Reputation: 15
I'm new to C++ and trying to figure this out. When I compile, I get the error a nonstatic member reference must be relative to a specific object
. What's the correct way of writing the code? This is what I have where numShapes
is giving me the error.
class Application
private:
int numShapes;
public:
Shapes * shapes[numShapes];
I then have this in another header as my virtual base class, if that's the correct term.
class Shapes
{
virtual void draw(char letter);
virtual ~Shapes() {}
};
Upvotes: 0
Views: 322
Reputation: 206717
Instead of
Shapes * shapes[numShapes];
I suggest the use of:
std::vector<Shapes*> shapes;
Remove numShapes
altogether since you can get the size from shapes
.
Initialize shapes
in the constructor. Something along the lines of the following should work.
Application::Application(std::size_t numShapes) : shapes(numShapes, nullptr) {}
Upvotes: 0
Reputation: 3965
The code Shapes * shapes[numShapes];
is requesting the compiler to reserve numShapes amount of space. The problem is that it does not have a known value at compile time. So either make numshapes
a constant, or look into dynamic memory allocation.
Upvotes: 1