Can I add default copies to the constructor?

Can I add default copies to the constructor?

Eg. For this class:

class A
{
    public:
        int a;
        int* b;
};

I want to just write

A::A(const A& rvalue):
    a(rvalue.a),
    b(new int(*(rvalue.b)))
{}

without part a(rvalue.a).

(Ignore bad / ugly code and possible memory leaks)

+5
source share
3 answers

What you ask for is impossible. Once you declare your own copy constructor, the compiler will not create a copy constructor for you. This means that you cannot simply add or increase the default copy constructor because it will not exist. This is all or nothing, so to speak.

+8
source

. , , , :

struct A1  {
  int a1;
  int a2;
  // ....
  int aN;
};

struct A:public A1
{
  int* b;
  A(const A& rhs):  A1(rhs), b(new int(*(rhs.b))) {}
};
+5

, , ++: .

, , :

, ( ..), :

//class A hasa large number date members(but all can take advantage of default 
//copy constructor
struct A{
    A(int i):a(i){}
    int a;
    //much more data memberS can use default copy constructor all in class A
};

//class B is simply wrapper for class A 
//so class B can use the default constructor of A
//while just write copy constructor for a raw pointer in it copy constructor
//I think this is what OP want ?
struct B
{
    B(int i,int j):m_a(i),m_b(new int(j)){}

    B(const B & rval):
    m_a(rval.m_a),
    m_b(new int(*rval.m_b))
    {
    }
    A     m_a;
    int * m_b;
};

int main()
{
    B c(2,3); // a=2, *m_b=3
    B d(c);   //after copy constructor, a=2, *m_b=3
}
+1

All Articles