开发者

c++ is this copy constructor?

开发者 https://www.devze.com 2023-02-16 21:54 出处:网络
class A {}; class B { public: B (A a) {} }; A a; B b=a; I开发者_JAVA技巧 read this from http://www.cplusplus.com/doc/tutorial/typecasting/ . It says this is a implicit type conversion. From class A
class A {};
class B { public: B (A a) {} };

A a;
B b=a;

I开发者_JAVA技巧 read this from http://www.cplusplus.com/doc/tutorial/typecasting/ . It says this is a implicit type conversion. From class A to class B. I want to ask, is this also an example of copy constructor? Thanks.


No, it's not a copy constructor. A copy constructor copies one object of one type into another of the same type:

B::B(const B& b)
{
    // ...
}

As a side note, if you need a copy constructor then you also need a destructor and an assignment operator, and probably a swap function.

What B::B(A) is is a conversion function. It's a constructor that allows you to convert an object of type A into an object of type B.

void f(const B& obj);

void g()
{
    A obja;
    B objb = obja;
    f(obja);
}


No, A copy constructor has the form

class A
{
public:
  A(const A& in) {...}
}


No, a copy constructor is called when you create a new variable from an object. What you have there is two objects of different types.


The line B b = a; implies that a copy constructor is used, as if you had typed B b = B(a); or B b((B(a)));. That is, the compiler will check whether B has an accessible (public) copy constructor - whether user-defined or the default one provided by the compiler. It doesn't mean, though, that the copy constructor has to be actually called, because the language allows compilers to optimize away redundant calls to constructors.

By adding a user-defined copy constructor to B and making it inaccessible, the same code should produce a compiler error:

class A {};
class B { 
public: 
    B (A ) {}
private:
    B (const B&) {} // <- this is the copy constructor
};

A a;
B b=a;

For example, Comeau says:

"ComeauTest.c", line 10: error: "B::B(const B &)" (declared at line 6), required
          for copy that was eliminated, is inaccessible
  B b=a;
      ^
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号