Theocharis K.
Theocharis K.

Reputation: 1341

Array of pointers to objects using the default constructor

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.

Upvotes: 1

Views: 745

Answers (3)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

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.

Upvotes: 2

mythagel
mythagel

Reputation: 1839

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).

Upvotes: 2

AJMansfield
AJMansfield

Reputation: 4129

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).

Upvotes: 0

Related Questions