Consider the given code
struct ABC
{
ABC()
{
std::cout<<" Calling from default constructor";
}
ABC(const ABC ©)
{
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With