mercredi 10 mars 2021

Error spotted in C++ Primer 5th Edition (copy intialization vs direct initialization)

Hi i am trying to understand how copy constructor works and looking at an example. The example is as follows:

{//new scope
Sales_data *p = new Sales_data;
auto p2 = make_shared<Saled_data>();
Sales_data item(*p); // copy constructor copies *p into item
vector<Sales_data> vec;
vec.push_back(*p2);// copies the object to which p2 points
delete p;
}

My question is :

  1. Why it is written that "copy constructor copies *p into item"? I mean, item is direct initialized. If we would have written Sales_data item = *p; then it will be called copy initialized, so why they have written copy constructor copies *p into item in the comment.

Now, to verify this for myself, i tried creating a simple example myself, but there also i am unable to understand the concept properly. My custom example is as follows:

#include<iostream>
#include<string>

class MAINCLASS{
  private:
    std::string name;
    int age =0;
  public:
    MAINCLASS(){
        std::cout<<"This is default initialization"<<std::endl;
    }
    MAINCLASS(MAINCLASS &obj){
        std::cout<<"This is direct initialization"<<std::endl;
    }
    MAINCLASS(const MAINCLASS &obj):name(obj.name),age(obj.age){
        std::cout<<"This is copy initialization"<<std::endl;
    }
};

int main(){
    MAINCLASS objectone;
    MAINCLASS objecttwo =objectone;
    MAINCLASS objectthree(objectone);
    return 0;
}

Now when i run this program, i get the following output:

This is defalut initialization

This is direct initialization

This is direct initialization

My question from this program is as follws:

  1. Why are we not getting the output "this is copy initialization" in the second case when i write MAINCLASS objecttwo =objectone;? I have read that in direct initialization function matching is used and in copy constructor , we copy the right hand operand members into left hand operand members. So when i write MAINCLASS objecttwo =objectone; it should call the copy constructor and print "this is copy initialization" on the screen. But instead it is direct initializing the object. What is happening here?

Aucun commentaire:

Enregistrer un commentaire