Assignment Operator Problem on Based and Derived Class

Discussion in 'C++' started by yccheok, Sep 11, 2008.

  1. yccheok

    yccheok Guest

    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/papers/cpp_report/the_anatomy_of_the_assignment_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::eek: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
     
    yccheok, Sep 11, 2008
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Karl Heinz Buchegger
    Replies:
    3
    Views:
    531
    Karl Heinz Buchegger
    Aug 6, 2003
  2. John Harrison
    Replies:
    0
    Views:
    492
    John Harrison
    Aug 6, 2003
  3. user
    Replies:
    1
    Views:
    403
    Jack Klein
    Jul 11, 2005
  4. Replies:
    1
    Views:
    396
    myork
    May 23, 2007
  5. Replies:
    1
    Views:
    389
    Victor Bazarov
    May 23, 2007
Loading...

Share This Page