Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > C++ > Assignment Operator Problem on Based and Derived Class

Reply
Thread Tools

Assignment Operator Problem on Based and Derived Class

 
 
yccheok
Guest
Posts: n/a
 
      09-11-2008
Hello all, I am confused on the correct assignment operator that
should be implemented on the derived class. I refer to the document
found at :-

http://www.icu-project.org/docs/pape..._operator.html

which the author recommence not using "virtual" for assignment
operator. Hence, I provide the following implementation.

#include <iostream>

using namespace std;

class B {
public:
B(int i) : b(i) {}

B& operator=(const B& me) {
if(&me == this) return *this;

b = me.b;

cout<< "b assignment"<< endl; return *this;
}

virtual void fun() { cout<< "b: " << b << endl; }

private:
int b;

};

class D: public B {
public:
D(int i) : B(i), d(i) {}

D& operator=(const D& me) {
if(&me == this) return *this;

d = me.d;

B:perator =(me); cout<< "d assignment"<< endl; return *this;
}

virtual void fun() { B::fun(); cout<< "d: " << d << endl; }

private:
int d;
};

int main()
{
cout<< "main"<< endl;

B* b0 = new D(100);
B* b1 = new D(200);

(*b0).fun(); // "b: 100"
// "d: 100"
// printed. Correct behavior.

*b0 = *b1; // "b assignment" printed. is this the correct
expectation?
// shall we expected "b assignment", followed by "d assignment"
// to be printed? If yes, what shall be the correct
implementation?

(*b0).fun(); // "b: 200"
// "d: 100"
// printed. Now the result is "half-baked". The based class are
// being assigned properly. However, the child class is not

delete b0;
delete b1;
}

It seems that for me, the assignment operator implementation for
derived class is not correct (At least it shall not produce "half-
baked result) May I know what shall the correct implementation for
that? Any suggestion are welcomed.

Thanks!

cheok
 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Derived::Derived(const Base&) and Derived& operator=(const Base&) developereo@hotmail.com C++ 1 05-23-2007 01:44 PM
Derived::Derived(const Base&) and Derived& operator=(const Base&) developereo@hotmail.com C++ 1 05-23-2007 12:07 AM
derived class and base class, member assignment, which goes first user C++ 1 07-11-2005 04:25 AM
Re: Copy assignment for derived class when base class has privatemembers Karl Heinz Buchegger C++ 3 08-06-2003 11:44 AM
Re: Copy assignment for derived class when base class has private members John Harrison C++ 0 08-06-2003 08:50 AM



Advertisments