1

I was thinking today while reading about the default constructor of classes in C++ and let's say we have this code of the class SortedArray:

class SortedArray
{

private:
    struct arrayCell
    {
        int pageID;                
        int totalNeighbors;   
    };
};

We assign an array of pointers pointing to objects of this class and then we initialize the pointers using the default constructor. What will happen? Will memory be stored for the structs? And if it is what will the int's be initialized to? Thanks.

2
  • The accepted answer is wrong, the ints will not be initialised unless you (zero|value)-initialise them. Commented Nov 2, 2012 at 4:31
  • @SethCarnegie You are completely correct, in fact there were several things that were incorrect. I have changed my answer accordingly. Commented Nov 4, 2012 at 22:53

3 Answers 3

2

OLD ANSWER: Im pretty sure that memory is created for that element, if you compile and run it there is no segmentation fault when accessing that memory. The ints will be set to the default value of 0.

Default constructor information can be found here.

EDIT: The above answer is incorrect. The code will not provide memory for the integer elements because the struct is defined but no object using the struct will be created unless you create one manually in which case the memory for those integers will be created.

As for the value of the created integers:

They will not be initialised to anything that makes sense they will simply contain what was in the memory before they were created.

Sign up to request clarification or add additional context in comments.

Comments

2

If you're talking about pointers of type SortedArray* then no.

SortedArray is an empty class with a private nested type.

If you allocate instances of the nested type SortedArray::arrayCell then the integers will be default-initialized (the value is unspecified).

Comments

0

I'm pretty sure it will allocate memory for each object you initialize in your array, with the ints set to their default value (0).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.