Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to initialize vectors in a class's contructor?

I am trying to create a class that has a member variable of type std::vector<std::pair<int, int>>.

Below is an example class that recreates my original class:

class temp {
private:
    vector<pair<int, int>> map;
public:
    temp() {
        vector<pair<int, int>> map(3, { 0, 0 });
    }

    void foo() {
        //Do something
    }
};

when I add the following line of code in the constructor of the above class, it throws no error:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

cout<<map[0].first<<" "<<map[0].second<<'\n';

However, when I add the same line of code in the function foo and call it like so:

temp map{};
map.foo();

it throws the following exception:
exception thrown when the last line of code is added to foo()

What am I doing wrong?

>Solution :

In your temp constructor you define a brand new and totally separate variable with the name map.

What you should use is a constructor initializer list:

temp()
    : map(3)
{
    // Empty
}

The above will initialize the vector using the constructor taking a size argument. This specific example means that map will be initialized with three default-constructed elements.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading