Search code examples
c++c++98

How do you access a member from a grandparent in a member function with a matching child member name?


I have a diamond problem setup with classes. For simplicity:

class   GrandParent
{
    public:
        ...
    protected:
        std::string name;
        int         age;
};

class   Parent1: virtual public GrandParent
{
    public:
        ...
};

class   Parent2: virtual public GrandParent
{
    public:
        ...
};

class   Child: public Parent1, public Parent2
{
    public:
        Child(void);
        Child(const Child & other);
        ~Child(void);
        Child & operator=(const Child & other);

    private:
        std::string name;
};

They each have Canonical Orthodox form, and some additional member functions.

My problem came up with the copy assignment operator of the Child class: (need help with what is in between double exlcamation marks !!)

Child & Child::operator=(const Child & other)
{
    std::cout << "Child Copy assignment operator called" << std::endl;
    if (this != &other)
    {
        name = !!other.name!!;
        GrandParent::name = !!other.name!!;
        GrandParent::age = other.age;
    }
    return (*this);
}

How would these be differentiated properly?


Solution

  • As I understand the question, it boils down to: how to refer to an eclipsed member variable via an object pointer or reference.

    The answer is to specify the originating class when referring to the variable:

    Child & Child::operator=(const Child & other)
    {
        std::cout << "Child Copy assignment operator called" << std::endl;
        if (this != &other)
        {
            name = other.Child::name;  // or just other.name which refers to the Child "name"
            GrandParent::name = other.GrandParent::name;
            GrandParent::age = other.age;
        }
        return (*this);
    }```