Skip to main content
gamedev.net
🔒 Locked

Untitled

Started by derek7 4 replies 550+ views
Original Post
derek7
derek7
class A { const maxcnt; int m_log[maxcnt]; A():maxcnt(100) }; compile not pass it. why? if I use global variable const maxcnt ,all is ok. what is different?
dustamulet
dustamulet
Try const int maxcnt; (or unsigned int or watever u want to use)
jpetrie
jpetrie
It's not legal C++.

1) Default-int is not supported by C++ (you must say "const TYPE maxcnt;" where type is probably int).

2) maxcnt is not a compile-time constant and cannot be used as the dimension of a static array. If you think about this, it should be obvious: with the right constructor, such as one that takes an int parameter and initialized maxcnt with that int, maxcnt can have different values per instantiation of A, which would allow for A's of differing sizes, which would break more language features than you'd care to think about. You'll need to use dynamic allocation or std::vector instead. The latter is preferable to the former; if you must use the former, consider an appropriate "smart" pointer object.

3) You actually have to give the constructor a body, even when you specify an initializer list (such as: "A():maxcnt(100) { }").
blarn
blarn
it'll work if you say

class A
{
static const int maxcnt = 100;
int m_log[maxcnt];
};

buut yeah you can't initialize 'maxcnt' in the constructor and use it as an array size or something.
dbzprogrammer
dbzprogrammer
Heap anyone?

class A{private:  int maxcnt;  char* m_log;public:  A() : maxcnt(100), m_log(new char[maxcnt])  {}  ~A()  {  delete[] m_log;  }}
We should do this the Microsoft way: "WAHOOOO!!! IT COMPILES! SHIP IT!"
Evil Steve
Evil Steve
Quote:
Original post by derek7
class A
{
const maxcnt;
int m_log[maxcnt];

A():maxcnt(100)
};
Let's assume that's valid C++ for a moment. What is the size of the object before it's constructed? What's the size of the object after it's constructed? sizeof() is evaluated at compile-time, but the size isn't known till runtime.
Basically, it won't work.

What you can do is:
class A{enum {maxcnt = 100};int m_log[maxcnt];A() {}};
But I'd second using the heap (Or a std::vector) here.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.