Sign in to follow this  

Please Help with C++ Class Object! (syntax error)

This topic is 4097 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello All! I try to initialize an Object of an Array class with a certain size in my other main Class, but it wont work that easy. My mainclass shortend looks like this.. class Ship { public: Ship(GLdouble initialPos_x=0, GLdouble intitialPos_y=0, bool initialControl=0, bool initialSelected=0, GLdouble initialAlignment=0, String initialTexture="shipmap.tga, 1", bool initialMouseOver=FALSE); Ship (const Ship &); ~Ship(); . .. ... private: . .. ... Array DevianceAngle; Array AngleToEnemies(32); . .. ... } And my Array Class looks like that: class Array { public: Array(int = 5); Array(const char *const); Array(const Array &); ~Array(); int getSize() const; float Array::GetLast(void); void Clean(int f, int l, float val); Array Clean(float val); Array Add(float num); Array Insert(int pos, float num); void SetSize (int s) { size = s;} float GetMax(void); float GetMin(void); void setVal(int num, float val); const Array &operator=( const Array & ); float &operator[]( int ); float operator[]( int ) const; bool operator==( const Array & ) const; bool operator!=( const Array &right ) const { return ! ( *this == right ); } private: int size; // pointer-based array size float *ptr; // pointer to first element of pointer-based array }; Array::Array( int arraySize ) { size = ( arraySize > 0 ? arraySize : 10 ); // validate arraySize ptr = new float[ size ]; // create space for pointer-based array for ( int i = 0; i < size; i++ ) ptr[ i ] = 0; } . .. ... Array DevianceAngle initializes just fine with the standard size = 5, but if I try to initialize AngeToEnemies it writes this message: E:\C++ Projects\Game\game.cpp(185) : error C2059: syntax error : 'constant' Why?? How can I initialize an Array Object in my Ship Class with a different size and without getting the syntax error? Please help.

Share this post


Link to post
Share on other sites
You can only specifiy constructor arguments when an object is being constructed. The line:

Array AngleToEnemies(32);

should be a declaration. You need to construct the AngleToEnemies object in the Ship constructor thus:

Ship::Ship (/*parameters*/) :
AngleToEnemies (32)
{
}

Skizz

PS use [ code ] or [ source ] tags, it really is useful!

PPS Mantear - that is valid code, it's an anonymous parameter. It's frowned upon because it doesn't give any indication of meaning.

Share this post


Link to post
Share on other sites
thanks for the reply but I still not exactly sure what you mean..

the error refers to: Array AngleToEnemies(32)

if I am outside my class I can easily initialize any Array Object of any size e.g. Array anArray(40);.. creates an Array of size 40.
But if I initialize in in Class, it stipulates the mentioned syntax error.

I still don't understand how to solve this problem... what should I change, to be able to initialize an Array object from my Array class in my Ship class with a size that is defined by brackets () ?

Share this post


Link to post
Share on other sites
I tried this now as suggested earlier

and still getting an errormessage..
E:\C++ Projects\Game\game.cpp(226) : error C2061: syntax error : identifier 'TestArray'

[ code ]

Ship::Ship(GLdouble initialPos_x, GLdouble initialPos_y, bool initialControl, bool initialSelected, GLdouble initialAlignment, String initialTexture, bool initialmouseover):Array TestArray (50)
{
shipnumber++;
pos_x = initialPos_x;
pos_y = initialPos_y;
control = initialControl;
selected = initialSelected;
alignment = initialAlignment;
shipTexture="warbird";
mouseover = initialmouseover;
SN=shipnumber;
AI=0;
}

Share this post


Link to post
Share on other sites
Hmmm, this is tricky to explain. It's all to do with the difference between declaration and instantiation. You can't provide any constructor arguments when declaring, only when you're instantiating. At global scope:

Array AngleToEnemies(32);

is an instantiation, you can provide a constructor parameter.

However:


class AClass
{
private:
Array AngleToEnemies;
};

Is a declaration and you can't provide a constructor parameter. The reason the above works is that the default constructor is called (=5) when an instance of AClass is instantiated. Therefore, the only place you can provide a constructor parameter to a member variable is in the constructor of the owning class:


class AClass
{
public:
AClass (void) :
AngleToEnemies (32) // this is the only place the parameter can be specified
{
}
private:
Array AngleToEnemies;
};

Try it and see. It's a complex idea to understand so you can either accept it as given or try searching for more in-depth descriptions of object construction.

Skizz

Share this post


Link to post
Share on other sites
Quote:
Original post by poliet
I tried this now as suggested earlier

and still getting an errormessage..
E:\C++ Projects\Game\game.cpp(226) : error C2061: syntax error : identifier 'TestArray'

[ code ]

Ship::Ship(GLdouble initialPos_x, GLdouble initialPos_y, bool initialControl, bool initialSelected, GLdouble initialAlignment, String initialTexture, bool initialmouseover):Array TestArray (50)


You still need to declare the member as you would any other member but without the constructor parameters, you need to initialise the object in the owning class' constructor using the form:

AClass::AClass :
member (constructor_parameters)
{
}

Skizz

Share this post


Link to post
Share on other sites
Quote:
Original post by Mantear
"Array(const char *const);"


That isn't declaring a variable named "const", it's specifying that the ctor takes a const pointer (meaning no ++ or -- =) to a const char.

Share this post


Link to post
Share on other sites
Since this is clearly C++ why are you using your own Array class instead of the standard, highly efficient dynamic-array class std::vector?

Σnigma

Share this post


Link to post
Share on other sites
Hmm... didn't know about that unit recently.. I was looking for an Array class that is dynamic, in which you can add elements without bothering too much about range, which calculates the min/max, can handle Strings etc., I couldn't find one on the Web, thus I created my own class

Can Vectors do this? What would be the advantage to my Array class?

Share this post


Link to post
Share on other sites
Quote:
Original post by poliet
in which you can add elements without bothering too much about range

Yes. std::vector resizes its internal storage dynamically allowing you to insert any number of items, up to maximum available memory.
Quote:
which calculates the min/max

No, but the standard library algorithms std::min_element and std::max_element are compatible with std::vector as well as all the other standard containers, plus raw arrays. Of course, if you want to get the largest and smallest element a lot then a std::set may be a better option. set keeps its contents sorted, so retrieving the smallest and largest elements are very quick. Iterating through the entire container is slower than a vector though.
Quote:
can handle Strings etc.

Yes. std::vector is templated so you can have a std::vector of anything that has normal copy semantics. Including std::strings.

Quote:
What would be the advantage to my Array class?

std::vector is standard. Which is enough of an advantage in itself. But on top of that, unless you thought to separate allocation from initialisation, provided for alternative allocators, implemented the empty-base optimisation among others and provided an iterator interface then std::vector will beat your Array class out on efficiency and generality too.

This is a good reference for part of the C++ Standard Library (it's actually for the Standard Template Library, which became a part of the C++ Standard Library, after a few minor changes).

Σnigma

Share this post


Link to post
Share on other sites
sounds like a good solution... unfortunatelly, I've just finished implementing my Array class to my prog.. Darn! Changing now everything back into using a vector class is probably not worth it. Next time I will know :)

Share this post


Link to post
Share on other sites
Although, after experimenting I need to say that. Definitely it was foolish NOT to use the Vector class in the first place, however I do OpenGL, and when I fumbled with Vectors and accessed a vector on a wrong position the programm terminated abnormally and it was difficult to see and determine where the mistake was.

Being highly inferior to the std vector class, the selfmade array class had one advantage though. I added mutliple "chrash"-securities in it, as well OpenGL Text error handling output, for accessing, data manipilation etc. and that's something I like about programming generally with C++.. when programming raw I can add as many member functions as I like and also do my own error handling and fuse it with any Interface, in this case OpenGL.
I might be old school, maybe a bloddy beginner or just never had proper C++ education, but if I don't write all the classes I need myself I feel always terribly lost.. But if I need functionality, I simply add something in my class, highly optimized for my main program. Since there are thousands of algorythms running on the computer simultaneously when 200 ships or so being displayed, I like to handle the output of my class myself, reducing the calculation of algorythms to an minimum or just making sure that everything is being accessed properly, in case I err is still being accessed properly.

I am sure there is of course something cool std out there that would do that for me to, but I do not have the time to learn all this and understand while I go on with my programm. But definitelly, next time I start a big project, I will definitelly consider vectors.

Share this post


Link to post
Share on other sites
I'm not sure what your issue was with errors, but I believe you are most likely not handling exceptions in your code. The STL std::vector throws exceptions that you can catch which covers anything you could possibly need.

Share this post


Link to post
Share on other sites
Quote:
Original post by poliet
Being highly inferior to the std vector class, the selfmade array class had one advantage though. I added mutliple "chrash"-securities in it,

Like setting the size of the array to 10 on invalid input? That's not secure, you should bail out as fast as possible without loosing information on invalid input.

Quote:
I like and also do my own error handling and fuse it with any Interface, in this case OpenGL.

std::vector on the other hand is smart and make a generic error handling interface, so that it works with OpenGL or whatever you use.

Quote:
I might be old school, maybe a bloddy beginner or just never had proper C++ education,

You just don't have enough experience.

Quote:
but if I don't write all the classes I need myself I feel always terribly lost..

Why do you use OpenGL then? I have a feeling you haven't written those functions.

Quote:
highly optimized for my main program.

I would like to see some of your most highly optimized code and compare it to the SC++L implementation. You might be surprised at the results, because I see many possible bottlenecks just in the little part of the Array class you posted.

Quote:
I am sure there is of course something cool std out there that would do that for me to, but I do not have the time to learn all this and understand while I go on with my programm. But definitelly, next time I start a big project, I will definitelly consider vectors.

To write a proper bug-free dynamic array implementation takes much longer than learning the vector interface. You could also ignore the int keyword, and use other stuff (short, maybe even get integer by using some "cool" hack), but really, is it worth it?

Share this post


Link to post
Share on other sites
I am not a guru or so. I just tried to do this I believe...

std::string Message = VectorOne.at(30);

and the program terminated abnormally (had to restart comp). I couldn't say why or how or at which line at the beginning, , nor did it display on my GL interface what was wrong.. I had already written dozends of vector codes... I mean, imagine that happens at a much later stage in developement, how much trouble I would have to find the right line later on...
I figured that at (30) it was not at all assigned, I dunno, but this caused my program to chrash. What I tried to say before is, I implemented securities in the Array Class in the way that if I try to access an element that is not valid or corrupt due to bad data (I am programming a Net Space game), the programm estimates the outcome, recovers it and also writes a OpenGL error message that it did and there is something wrong... I would never say that a self made Array class in better, just I am prolly not good enough to use all that std library stuff yet.

Share this post


Link to post
Share on other sites
Quote:
Original post by poliet
I am not a guru or so. I just tried to do this I believe...

std::string Message = VectorOne.at(30);

and the program terminated abnormally (had to restart comp).


What OS are you using? It shouldn't be possible to cause that on anything modern, at least not without a *lot* of *deliberate* effort.

Quote:
just I am prolly not good enough to use all that std library stuff yet.


It's the standard library for the language you are using. It is only the smallest possible step removed from actually being built in to the langauge. Therefore, if you can't use it right, it's not a matter of talent but of actually knowing the language. You may need to go back and relearn a hell of a lot. This is sadly the case for a very, very large number of C++ programmers, in part because of the language history.

Share this post


Link to post
Share on other sites
poliet please read my post up there because it tells you exactly why the program is crashing and exiting. Learn one of the core features of C++, exception handling, and you won't have any problems using or debugging stl containers.

Share this post


Link to post
Share on other sites

This topic is 4097 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this