Search code examples
c++stdlist

Constructor not getting called


I am making an array of 4 std::list. But when I try to access the array's first list's first A object and call the callMe() method on it I get a weird output.

Now 2 things could have happened:

  1. Either the list was empty.
  2. An A object was created when I tried to access the first element of the first list((*(arrayOflistOfA[0].begin()))).

Details of the above cases:

  1. If no A object was created then I should have got an exception. But I didn't get any exception so I am assuming that an A object was created.
  2. So if an A object was indeed created, then the constructor should have been called.

What am I missing?

#include <iostream>
using namespace std;
class A {
public:
    A() {
        cout<<"Constructor called"<<endl;
        x=20;
    }
    void callMe();
private:
    int x;
};

void A::callMe() {
    cout<<"Value of x = "<<x<<endl;
}

int main() {
    const int size = 4;
    list<A>* arrayOflistOfA = new list<A>[size];
    (*(arrayOflistOfA[0].begin())).callMe();
}

The output is:

Value of x = 0

but the output should have been:

Constructor called
Value of x = 20

Solution

  • If no A object was created then I should have got an exception.

    Not true.

    But I didn't get any exception so I am assuming that an A object was created.

    Don't assume. Find out. Go to some documentation for begin() and for iterators and discover that you do not get an exception, you get UB.

    An A object was created when I tried to access the first element of the first list((*(arrayOflistOfA[0].begin()))). [And] if an A object was indeed created, then the constructor should have been called.

    That's right. Clearly you have no elements in the list.

    And we know that, because there is no code in your program that adds elements to the list.

    Also you should not dynamically allocate containers unless you really, really need to (I've never found a need to).