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

48 Views Asked by At

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?

2

There are 2 best solutions below

0
nielsen On BEST ANSWER

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);
}```
0
Sam Varshavchik On

Well, for starters, the shown code does not require a user-defined assignment operator. The default one will do the right thing, so: forget the whole thing. But, presumably, there must be a reason for one, hence the task at hand.

One simple way is to spoon-feed every step to your C++ compiler:

const GrandParent &other_grandparent=other;

GrandParent::name = other_grandparent.name;

And, of course, if only the Child requires a user-defined assignment operator, for some reason, but the grandparent's default assignment operator does the job, then simply do that:

GrandParent::operator=(other);