Sunday, May 08, 2005

C++ Object Creation

See to this code and try guessing the output

#include
using namespace std;

class Parent {

protected:
int num_p;
public:
Parent () : num_p (0) { }
Parent (const Parent& r) { num_p = r.num_p; }
int GetNumP () { return num_p; }
void SetNumP (int n) { num_p = n;}
};


class Child : public Parent {

protected:
int num_c;
public:
Child () : num_c (0) { }
Child (const Child& r) { num_c = r.num_c;}
int GetNumC () { return num_c;}
void SetNumC (int n) { num_c = n; }
};


int main( )
{

Child obj;
obj.SetNumP (10);
obj.SetNumC (20);

Child test = obj;
cout << test.GetNumP << " " << test.GetNumC ();
return 0;
}


The first thing that everyone says is that output is: 10 20. However the ouptut is: 0 20.
The reason for this is that the author of the code has forgotten to call the copy constructor of the parent from the copy constructor of the child. We usually do call the Base Class constructors from default constructors but mostly forget to do the same when dealing with copy constructors.

The reason for this output is that the parent object has to be created before creation of Child Object. So when copy constructor is called, it wants to call the constructor of the base class. However as no constructor is mentioned by the author of child class, it choses to call the default constructorof the base class that assigns 0.

I dont think that the correct solution .. rather corrected line is difficult enough to guess now. Write something like as the copy constructor of child class

Child (const Child& r) : Parent (r){
num_c = r.num_c;
}

Cheers!

0 Comments:

Post a Comment

<< Home