Practice mode C++

Assuming standard headers and using namespace std, what does this C++ code print? struct P { P() { cout << “D”; } P(const P&) { cout << “C”; } }; int main() { P a; P b = a; P c; c = b; }

Correct answer B. DCD

Explanation

P a runs the default constructor (D). P b = a is initialisation of a new object from an existing one, so the copy constructor runs (C). P c prints D. The final line c = b assigns to an object that already exists, so the implicitly generated copy assignment operator runs, which prints nothing. Initialisation and assignment use different special member functions.

Report a problem

Answer checked How we write and check questions

Tip: press A, B, C or D to answer, and N for the next question.

Advertisement

Have a question about this answer?

Your email address will not be published. Required fields are marked *

Links and website addresses are not allowed in comments.