Jump to content
  • Advertisement
Sign in to follow this  
jujumbura

C++ arrays, blocks of structs and construtors?

This topic is 4369 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
Advertisement
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.getInt() << std::endl;
}

for(int i = 0; i < 5; i++)
{
std::cout << "onHeap[" << i << "].getInt() returned " << onHeap.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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!