views:

57

answers:

2

I have a class Derived which is derived from class Base. In Derived's function, I can access protected members of Base. E.g., I can do this.

class Base
{
protected:
    int i;
}

class Derived : class Base
{
    void process()
    {
        i = 5;
    }
}

My question is, is it possible to enforce the use of scope resolution operator when accessing base class member from derived class? The reason is that I want to make it clear in the code which variables are from the base class. The enforcement is so that I won't accidentally skip the scope resolution operator (I'm careless). I prefer not to use accessors since many members from the base class are required in the Derived class, making it tedious to code. I'm using MSVC 2010 by the way.

class Base
{
protected:
    int i;
}

class Derived : class Base
{
    void process()
    {
        Base::i = 5;   //enforce so that i=5 won't compile
    }
}
A: 

You cannot do it in the base class itself, no, there is no way you could enforce that. However, I am thinking of a trick which you could do in a derived class to enforce what you want, that is, if you declare a variable with the same name i in the derived class as a member, but of type, say, MyBadType, which is just an empty type, then i in derived will refer to it and there is really nothing the user could do with it. So he will HAVE TO qualify to get the base i. But this is naturally a joke, I mean, you don't want to fatten the size of your derived class just to enforce qualified names. Your goal itself is a bit dubious.

HTH, Armen

Armen Tsirunyan
This would not work if the derived class actually has a valid data-member with the same name.
Space_C0wb0y
If the derived class DOES have a valid data member with the same name, then the trick is already done, I mean then the user has to qualify the name to get to the base member, right?
Armen Tsirunyan
@Armen: That is right, I did not think that through.
Space_C0wb0y
@Armen: A little hint: When responding to a comment use `@username`, so the addressed user gets a notification.
Space_C0wb0y
@Space_C0wb0y Thanks :)
Armen Tsirunyan
+1  A: 

you can simulate it by introducing another scope:

class Base {
protected:
    struct Data {int i;};
    Data d_Base;
};

class Derived : class Base {
    void process() {
        d_Base.i = 5;
    }
};
Justin