How the vector of class objects is initialized

There is a class screen in the code below. With elements: cursor position, screen width, screen height and screen content. It has another Window_mgr class, the list of which is a set of screens. Each screen has a specific position in the vector. I mark the line in the code with an arrow, so you do not need to go through the complete code.

My question is when we list the initializing vector (suppose int), we just do this:

std::vector<int> ivec{1, 2, 3, 4};

But in the code below, I initialize the type vector of the Screen object. What does it mean:

VECTOR screens = VECTOR{ {Screen(24, 80, ' '), Screen(32, 56, 'r') }};

I am only talking about members inside list initialization. that is, the screen (24, 80, ``) and the screen (32, 56, 'r'). Do they call the constructor version for the Screen class? As the constructor is called without creating an object. In my opinion, it should have been:

{Screen sr1(24, 80, ' '), Screen sr2(32, 56, 'r')}

Or simply

{(24, 80, ' '), (32, 56, 'r')}

I did a search over the Internet, but could not understand the concept. Thanks

#include <iostream>
#include <string>
#include <vector>

class Screen{
public:
    using pos = std::string::size_type; 

    Screen() = default; 
    Screen(pos ht, pos wd, char c) : 
        height(ht), width(wd), contents(ht *wd, c)  //in-class initializer
    {}

    char get() const { return contents[cursor]; }
    inline char get(pos ht, pos wd) const;

    Screen &set(char);
    Screen &set(pos, pos, char);

    Screen &move(pos r, pos c); 

    void some_member() const; 

private:
    pos cursor = 0; 
    pos height = 0, width = 0; 
    std::string contents; 
    mutable size_t access_ctr;
};


inline Screen &Screen::set(char c)
{
    contents[cursor] = c; 
    return *this; 
}

inline Screen &Screen::set(pos r, pos c, char ch)
{
    contents[r*width + c] = ch; 
    *this; 
}


void Screen::some_member() const
{
    ++access_ctr; 
}

inline Screen &Screen::move(pos r, pos c)
{
    pos row = r *width; 
    cursor = row + c; 
    return *this;
}

char Screen::get(pos r, pos c) const
{
    pos row = r * width;  
    return contents[row + c];
}    

//---------------------------------
class Window_mgr{
private:
    using VECTOR = std::vector<Screen> ;
    // A Window Manager has has one standard sized blank Screen
    VECTOR screens = VECTOR{ {Screen(24, 80, ' '), Screen(32, 56, 'r') }};  // <-----------------

};
//---------------------------------

int main()
{
    Screen scr{13, 33, 'c'};

    std::cout << scr.get(3, 1); 

    Window_mgr win{}; 


    return 0; 
}
+4
source share
1 answer

In C ++, it is quite suitable for building an instance of the inline class with a method call (essentially creating an anonymous class instance). So the syntax is

VECTOR{ {Screen(24, 80, ' '), Screen(32, 56, 'r') }}

VECTOR Screen. VECTOR ; move 'd , - .

+2

All Articles