Sign in to follow this  

C++ arrays, blocks of structs and construtors?

This topic is 4093 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

Hi guys, I have a struct question that I'd love to get some help with. Suppose I have a struct with a default constructor like so: struct A { public: A() : m_Int(0) {} int getInt() { return m_Int; } private: int m_Int; } Now, suppose I create an array of these structs like so: A structs[5]; Or, suppose I allocate them dynamically with new: A *pStructs = new A[5]; My question is, did it call the default constructor on the A's in the array and on the heap? Should all of their "m_Int"'s be set to zero? Thanks much for any feedback, jujumbura

Share this post


Link to post
Share on other sites
Well... this is a typical try-it-yourself question.
Try this, see what I mean?

#include <iostream>


struct A {
public:
A() : m_Int(0)
{
std::cout << "Printed on call of default constructor" << std::endl;
}

int getInt() { return m_Int; }

private:
int m_Int;
};


int main()
{
std::cout << "Allocating on stack:" << std::endl;
A onStack[5];

std::cout << "Allocating on heap:" << std::endl;
A* onHeap = new A[5];

//extra check
for(int i = 0; i < 5; i++)
{
std::cout << "onStack[" << i << "].getInt() returned " << onStack[i].getInt() << std::endl;
}

for(int i = 0; i < 5; i++)
{
std::cout << "onHeap[" << i << "].getInt() returned " << onHeap[i].getInt() << std::endl;
}


delete [] onHeap;
return 0;
}



[Edited by - Kalasjniekof on October 5, 2006 5:47:14 AM]

Share this post


Link to post
Share on other sites
Don't be too harsh -- remember, "try it yourself" can just as easily give you the wrong answer or impression as it can the right one; it would have perhaps been better for the OP to try an example, and then describe what he saw and ask if that behavior is standard and or guaranteed. But, especially with C++, it is very easy to get the wrong answer this way.

Consider the question: after execution of x = ++x, what value does x have?
This is a classic example of where "trying it yourself" can lead you astray.

Share this post


Link to post
Share on other sites

This topic is 4093 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