Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't understand class constructor

I have a class.

class Books
{
private:
    int m_books;
public:
    Books(int books=0)
    {
        m_books = books;
    }

    Books(const Books &source)  //Here is what I don't understand.
    {
        m_books = source.m_books;
    }
};

I can't understand why it has to be Books(const Books &source), and not Books(const Books source).

like image 490
Some Stranger Avatar asked Aug 01 '26 08:08

Some Stranger


1 Answers

When you have

Books(const Books &source)

the source is passed by reference. When you have

Books(const Books source)

it would have been passed by value. But to pass by value you are the copy constructor. So to avoid an infinite recursion, the copy constructor must accept a reference.

like image 103
AProgrammer Avatar answered Aug 03 '26 23:08

AProgrammer