Xenoprimate
Xenoprimate

Reputation: 7963

Why does this code invoke the copy constructor?

I'm a C++ noob so I can't figure out why the line in Logger.cpp invokes the copy constructor...

Logger.h:

class Logger {
    public:
    Logger();
    ~Logger();
};

Logger LOGGER;

Logger.cpp:

Logger LOGGER = Logger(); // Copy constructor here

Upvotes: 2

Views: 126

Answers (4)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

There is no enough code that to make some conclusion. It is not clear whether LOGGER in the header and in the module are defined in the same declarative region or in different declarative regions. In any case either the compiler shall issue an error or these two definitions define different objects for example because they are in different declaration regions.

Upvotes: 0

Joe Z
Joe Z

Reputation: 17936

The statement Logger() creates an anonymous temporary object.

LOGGER = Logger() copies that anonymous temporary into the object LOGGER. The copy constructor avoids having to construct LOGGER as something other than a copy of that temporary.

The compiler is allowed to optimize away this copy, but it's not required to. More here.

If you want to construct the object directly, just say Logger LOGGER;.

Upvotes: 10

Ravnock
Ravnock

Reputation: 1

"Logger();" is returning an object, then the assignment operator is called, which is calling the copy constructor. The previous LOGGER object is passed as a parameter.

Upvotes: -1

Bathsheba
Bathsheba

Reputation: 234635

In the statement Logger LOGGER = Logger(); the copy constructor is used.

Initially that seems surprising: you'd think that the assignment operator is used. But the language does not work that way. The reason is subtle: use of the assignment operator presupposes the existence of an object to which the assignment should be made. That would require default construction and that would be suboptimal.

Upvotes: 3

Related Questions