简体   繁体   中英

Calling a copy ctor and another ctor

I have a copy constructor defined in my code which is initializing data members of the object being created. Now If I have to just change the value of the few variables, I am writing a new copy ctor. So my question is, instead of again writing same code, can i just initialize particular different data members and for others, i can just call the defined one ctor in my ctor method.

example: Already present

A::A(const A& cpy)
{ 
 a=cpy.a;
 b=cpy.b;
 c=cpy.c
}

Now I want to write my ctor as

A::A(const A& cpy, bool x)
{
   if( x)
      a=something;
   else
      a =cpy.a
   //call first ctor for other variables (b and c)
}

Thanks Ruchi

Since C++11 you may do something like this:

class A 
{
    public:

          A(const A& cpy) { a=cpy.a; b=cpy.b; c=cpy.c; }  
          A(const A& cpy, bool x): A(cpy) { a = something_else; }  
}

You can do that by having a default argument in your copy constructor like

A::A(const A& cpy, bool x = false)
{
   if( x)
      a=something;
   else
      a =cpy.a
   //call first ctor for other variables (b and c)
}

you can invoke it like

A objA;
 A b(objA, true);       // b gets a shallow copy of a

A copy constructor may have defaulted further arguments:

A::A(A const & rhs, bool x = false)
{
    a = x ? FOO : BAR;
}

Maybe that helps you write your code succinctly...

In C++11 you can call constructors in initializer lists:

class Foo
{
public:
    Foo(int a) {}
    Foo(int a, int b) : Foo(a) {}
};

However, there is a problem with your code, and that is that you try to create a copy constructor that takes an extra argument. It is then no longer a copy constructor, but a normal constructor that takes two arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM