|
From: Per W. <pw...@ia...> - 2007-07-20 09:46:17
|
Several problems with the code - below are a couple of them:
1) No fread() in this code, so obviously no fread can get stuck.
2) The copy-constructor copies a pointer, making multiple objects point to
the same int buffer. What do you think happen when the first object gets
destroyed, and the destructor releases this shared memory?
3) The get() function takes an object by value, i.e. it creates a new
temporary object. What happens when this temporary object is destroyed?
Will the get() function every be able to return back an object (if now
get() is expected to read an object from file or similar)?
4) Don't you think that the destructor should use predecrement of the
count static member, so that when the last object is destroyed, the count
value 0 is printed?
5) If you impelemnt a copy constructor, where is the assignment operator?
/pwm
On 20 Jul 2007, Peeyush Bishnoi wrote:
> Hello All
> I am facing one problem in code below. This code is for copy constructor.
>
> Actaully when copy constructor gets called for get function with object b , the object value becomes 0. I think that that object b & object p are not pointing to same location as i explicitly declared the copy constructor.
>
> Please explain why it is so... Why object b value become 0 . Also how to avoid this so that object value should print actual value.
>
> #include<iostream>
> using namespace std;
> class A{
> static int count;
> int *num;
> public:
> A():num(new int(2)){
> cout<<"Zero argument ctor called\n"<<endl;
> count++;
> }
>
> A(int i):num(new int(i)){
> cout<<"One arument ctor called\n"<<endl;
> count++;
> }
>
> A(const A &i):num(i.num){
> cout<<"Copy Ctor called\n"<<endl;
> count++;
> }
>
> void print(){
>
> cout<<"count"<<count<<"Value:"<<*num<<endl;
> }
>
> ~A(){
> cout<<"Dtor called\t"<<"count"<<count--<<endl;
> delete num;
> }
> };
>
> void get(A p){
> cout<<"get function called\n"<<endl;
> p.print();
> }
>
>
> int A::count;
>
> int main(){
>
> A a;
> a.print();
> A b(3);
> b.print();
> get(b);
> b.print();
> A c=a;
> c.print();
> return 0;
> }
>
>
> Regards
> Peeyush B.
>
>
|