Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

No call to the copy constructor [duplicate]

Tags:

c++

Consider the given code

struct ABC
{
    ABC()
    {
        std::cout<<" Calling from default constructor";
    }

    ABC(const ABC &copy)
    {
        std::cout<<"Calling from copy constructor";
    }
};

int main()
{
    ABC abc = ABC();
}

I have two questions


Q1) Removing const from the copy constructor parameter declaration gives error. Why?

Q2) After adding the const keyword I dont see a call to the copy constructor. Why? The copy constructor does not get called so why is the const necessary?


TIA

like image 550
Ram Gandhi Avatar asked Nov 27 '10 14:11

Ram Gandhi


1 Answers

  1. You need the const because you try to initialize abc with a temporary ABC() which is const. Hence if the constructor is not const the compiler must reject the code.

  2. After you make it const the code is standard complaint and the compiler can compile it. However it's allowed to optimize out the copy in this case as said in the standard, so it removes the call to the copy constructor.

like image 94
Yakov Galka Avatar answered Oct 24 '22 18:10

Yakov Galka