What function will it call?

Here is the code, I wrote comments. The question is, I don’t know which function will be called after the unhide function in the Derive class.

    #include <CONIO.H>
    #include <IOSTREAM>
    #include <string>

    using namespace std;

    class Base
    {
        string strName;
    public:
        Base& operator=(const Base &b)
        {
            this->strName = b.strName;
            cout << "copy assignment" << endl;
            return *this;
        }
        Base& operator=(string& str)
        {
            this->strName = str;
            cout << "operator=(string& str)" << endl;
            return *this;
        }

    };

    class Derive : public Base
    {
    public:
        int num;
        using Base::operator =; // unhide Base::operator=();
    };

    int main(int argc, char *argv[])
    {
        Derive derive1;
        derive1.num = 1;

        Derive derive2;

        Base b1;
        derive1 = b1;  // This will call Base& Base::operator=(const Base &b)
                           //no problem

        string str("test");
        derive1 = str;  // This will call Base& Base::operator=(string& str)
                            // no problem

        derive2 = derive1; // What function will this statement call???
                               // If it calls Base& Base::operator(const Base &b)
                               // how could it be assigend to a class Derive?
        return 0;
    }

But the result of the code is: derive2.num is 1 !!!, this means that the whole class was copied after the statement, why would this happen?

Thanks to Tony, I think I got the answer.

here is my explanation:

Based on C ++ 0x 7.3.3.3 and 12.8.10, the usage description in Derivewill be explained as follows:

class Derive : public Base
{
public:
    int num;
    //using Base::operator =;
    Base& operator=(const Base &b); // comes form the using-statement
    Base& operator=(string& str); // comes form the using-statement
    Derive& operator=(const Derive &); // implicitly declared by complier
};

So when I wrote:

string str("test");
derive1 = str;

function Base& Base::operator=(string& str);will be called

and when I wrote:

Base b1;
derive1 = b1;

function Base& Base::operator=(const Base &b);will be called

finnaly when I wrote:

derive2 = derive1;

function Derive& Dervie::operator=(const Derive&);will be called.

+3
source share
2 answers

7.3.3-4 ( , ):

, , (class.copy), - ; - , .

, Derived::operator=().

+3

operator=, operator= Base, Derive.

+1

All Articles