xom9ikk
xom9ikk

Reputation: 2289

Can not initialize an array in the copy constructor

I have a class

class TTable
{
private:
    std::string tableName;
public:
    TRow rows[10]; //this other class TRow
    TTable(const TTable&);
    int countRows = 0;
};

And I implement the copy constructor

TTable::TTable(const TTable& table) : tableName(table.tableName), countRows(table.countRows), rows(table.rows) 
{
    cout << "Copy constructor for: " << table.GetName() << endl;
    tableName = table.GetName() + "(copy)";
    countRows = table.countRows;
    for (int i = 0; i < 10; i++)
    {
        rows[i] = table.rows[i];
    }
}

But the compiler curses on this rows(table.rows). How to initialize an array? With the variables everything goes, everything is good. Thank.

Upvotes: 2

Views: 957

Answers (2)

user0042
user0042

Reputation: 8018

Since raw arrays aren't copyable this way, use std::aray<TRow,10> rows; instead:

class TTable
{
private:
    std::string tableName;
public:
    std::array<TRow,10> rows;
    TTable(const TTable&);
    int countRows = 0;
};

TTable::TTable(const TTable& table) 
: tableName(table.tableName + "(copy)")
, countRows(table.countRows)
, rows(table.rows)  {
    cout << "Copy constructor for: " << table.GetName() << endl;
}

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726599

Your code does double-duty: in addition to copying in the body of the constructor, it also copies in the initialization list.

You don't have to do that: keep items that can be copied by the initializer list on the list, and remove them from the body; remove other items from initializer list:

TTable::TTable(const TTable& table)
:   tableName(table.tableName + "(copy)")
,   countRows(table.countRows)
{
    cout << "Copy constructor for: " << table.GetName() << endl;
    for (int i = 0; i < 10; i++) {
        rows[i] = table.rows[i];
    }
}

Above, tableName and countRows are initialized using the list, while rows are initialized in with a loop in the body.

Upvotes: 5

Related Questions