views:

89

answers:

4

Hello StackOverflowers,

With a friend, we had following problem recently. There was a base class:

class A {
public:
    A() : foo(10) {}
    virtual int getFoo() const { return foo; }

protected:
    int foo;
};

A friend implemented a class deriving from the one above.

class B : public A {
public:
    void process() { foo = 666; }
protected:
    //int foo;
};

Unfortunatelly he also added field foo in descendent class (commented line). So the following code.

#include <iostream>

int main()
{
    A* aaa= NULL;
    if (1) {
        B* bbb = new B;
        bbb->process();
        aaa = bbb;
    }

    std::cout << aaa->getFoo() << std::endl;

    return 0;
}

printed 10.

That's not the problem, since this will be totally redesigned, and such things won't happen in future.

I was just wondering, do you know any (portable) tricks or language patterns (besides obvious getters/setters; btw they were there actually, with foo being private), that would disallow declaring variable with the same name in descendent class (e.g. by causing compile-time error).

TIA!

+1  A: 

C++ doesn't have a lot of features to protect you from mistakes. It doesn't really have any way to know what you intended and so can't tell what is really a mistake.

Jay
Actually, it has a huge number of features to protect you from mistakes - more than most other languages. But not in this case, because it is not a mistake.
anon
+6  A: 

No - you are not supposed to care about the implementation of the base class, so you should not be constrained in naming members in your derived class. And protected data is a bad idea.

anon
as I've already stated, in reality foo was private
GiM
+3  A: 

You can make all your variables private then it doesn't matter if variables have the same name in descended classes, you'll always be accessing the correct variable - much better encapsulation which in turn will make your code easier to maintain in the long run.

PS : your test case does not need to be so complicated:

B b;
b.process();
b.getfoo();

will return 10 as well

Patrick
yeah I know, problem is the foo added in B was definitelly a mistakethanks for pointing out code simplication
GiM
A: 

Not in the language itself, but some compilers can be configured to report certain types of warnings as errors. Consult your compilers documentation for reference.

Axel