1

I have a base class

class Base{
public:
virtual ~Base();

};

I derive two classes from Base:

class D1:public Base{
//...some fields
//assignment operator, it does the deep copy of the members
D1& operator=(const D1&);
};

class D2:public Base{
//...some fields
//assignment operator, it does the deep copy of the members
D2& operator=(const D2&);
};

Next, in main I have two objects of let's say D1. The problem is that the overriden assignment operator is never called, however default one for base is called. I tried to make assignment operator virtual in Base, but it didn't help.

D1 *d1 = new D1();
D1 *d1_another = new D1();
//this doesn't work:
d1 = d1_another

D2 *d2 = new D2();
D2 *d2_another = new D2();
//this doesn't work:
d2 = d2_another

UPD Also I would like to know how to deal with

Base *d1 = new D1();
Base *d1_another = new D1();
//?
d1 = d1_another

1 Answers1

1

Try it like this

#include <iostream>
#include <string>

using namespace std;

class Base {
    public:
    virtual ~Base() {}

};


class D1 : public Base {
public:
    virtual ~D1() {}
    //...some fields
    //assignment operator, it does the deep copy of the members
    D1& operator=(const D1&) {
        cout << "D1:operator=(const D1&)\n";
        return *this;
    }
};

class D2 : public Base {
public:
    virtual ~D2() {}
    //...some fields
    //assignment operator, it does the deep copy of the members
    D2& operator=(const D2&) {
        cout << "D2:operator=(const D2&)\n";
        return *this;
    }
};

main

    D1 *d1 = new D1();
    D1 *d1_another = new D1();
    //this doesn't work:
    *d1 = *d1_another;

    D2 *d2 = new D2();
    D2 *d2_another = new D2();
    //this doesn't work:
    *d2 = *d2_another;
Hamza.S
  • 1,243
  • 8
  • 18