2

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.

0

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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;
}

6 Comments

An error in std :: array <TRow, 10> rows; Incomplete Incomplete Type
Use #include <array> and be sure that TRow is competely declared before using it.
Thank you. This is what I needed
@Xom9ik You can omit the explicit declaration and definition of that copy constructor completely BTW, if you don't need the debug output any more. The compiler will generate a working one automatically for you.
@juanchopanza Yes, but not using rows(table.rows) in the member initialization list.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.