Click here to Skip to main content
15,900,511 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C++
class Stack
{
    int *ptrStack;
    int top;
    int size;

public:
    Stack(int = 10);                    // Default Constructor
};

Stack::Stack(int s): size(s > 0 ? s ? : 10), top(-1), ptrStack (new int[size])
{
     // Body
}

main()
{
     Stack<integer> intStack(7);
}

As I Run the above sample, I get the Debug Error: Invalid Allocation Size. By debugging the sample, I came to know that "size" is not initializes and take some garbage value.
please correct the mistake, I made.

Thanks
Abid
Posted
Updated 19-Apr-11 23:15pm
v2
Comments
Sandeep Mewara 20-Apr-11 4:59am    
Looks incomplete code and question.

Can you please edit and update it. Be a little elaborate on the issue and code used.
Aabid 20-Apr-11 5:09am    
[Removed the code from here]
Sandeep Mewara 20-Apr-11 5:15am    
Updated it for you.
Olivier Levrey 20-Apr-11 5:01am    
Please update your question and your code. We can't help with that.
Aabid 20-Apr-11 5:07am    
[Removed code from here]

Aabid wrote:
size(s > 0 ? s ? : 10)

The above should be:
C++
size(s > 0 ? s : 10)
 
Share this answer
 
Comments
Olivier Levrey 20-Apr-11 5:34am    
My 5.
Sergey Alexandrovich Kryukov 20-Apr-11 17:49pm    
My 5 too,
--SA
The member variables are initialized in the order they are defined in the class definition, not in the order they appear in the constructor's initialization list. http://codewrangler.home.comcast.net/~codewrangler/tech_info/ctor_init.html#InitializationOrder[^]
http://www.goingware.com/tips/parameters/membervars.html[^]
This causes ptrStack to be initialized first, while size is still undefined. Rearrange your class definition to:
class Stack
{
    int size;
    int top;
    int *ptrStack;
public:
    Stack(int = 10);                    // Default Constructor
};
 
Share this answer
 
Comments
Niklas L 20-Apr-11 6:53am    
Nice catch!
Aabid 20-Apr-11 8:23am    
Thanks, Niklas!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900