C++ arrays, blocks of structs and construtors?

Started by
2 comments, last by jpetrie 17 years, 6 months ago
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
Advertisement
Yes, the default constructor is called.
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]
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.

This topic is closed to new replies.

Advertisement