Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Do we have to explicitly define a default constructor when we define a copy constructor for a class?? Please give reasons.

eg:

class A 
{
    int i;

    public:
           A(A& a)
           {
               i = a.i; //Ok this is corrected....
           }

           A() { } //Is this required if we write the above copy constructor??
};      

Also, if we define any other parameterized constructor for a class other than the copy constructor, do we also have to define the default constructor?? Consider the above code without the copy constructor and replace it with

A(int z)
{
    z.i = 10;
}

Alrite....After seeing the answers I wrote the following program.

#include <iostream>

using namespace std;

class X
{
    int i;

    public:
            //X();
            X(int ii);
            void print();
};

//X::X() { }

X::X(int ii)
{
    i = ii;
}


void X::print()
{
    cout<<"i = "<<i<<endl;
}

int main(void)
{
    X x(10);
  //X x1;
    x.print();
  //x1.print();
}

ANd this program seems to be working fine without the default constructor. Please explain why is this the case?? I am really confused with the concept.....

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
209 views
Welcome To Ask or Share your Answers For Others

1 Answer

Yes. Once you explicitly declare absolutely any constructor for a class, the compiler stops providing the implicit default constructor. If you still need the default constructor, you have to explicitly declare and define it yourself.

P.S. It is possible to write a copy constructor (or conversion constructor, or any other constructor) that is also default constructor. If your new constructor falls into that category, there's no need to provide an additional default constructor anymore :)

For example:

// Just a sketch of one possible technique    
struct S {
  S(const S&);
  S(int) {}
};

S dummy(0);

S::S(const S& = dummy) {
}

In the above example the copy constructor is at the same time the default constructor.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...