开发者

Disallow fields in descended class C++

开发者 https://www.devze.com 2023-01-09 00:57 出处:网络
With a friend, we had following problem recently. There was a base class: class A { public: A() : foo(10) {}

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!


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.


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


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消