Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making sure the method declaration is inherited

Tags:

c++

How can I protect from accidental definition of non-inherited method where inherited definition is intended. I am told there is trick to express it, but nobody can recall it.

Explanation. I have tree of classes: 'Base' <- 'C' <- 'D', below. Base defines pure virtual function. The function gets redefined in C then in D. But the function has very long argument list.

Somewhere along chain of derivation, there is subtle error in the agrglist which makes D:: non-inherited. Program hapily compiles. And the wrong method is called in the run-time.
Is there trick to cause compilation error when method is non-inherited.

#include <iostream>

class Base {
public:
    virtual void VeryLongFunctionName(int VeryLongArgumentList) = 0;
};
class C : public Base {
public:
    void VeryLongFunctionName(int VeryLongArgumentList) {
        std::cout << "C::\n";
    }
};
class D : public C {
public:
    void VeryLongFunctionNane(int VeryLongArgumentList) { // typo is intentional. It's the point of the question.
        std::cout << "D::\n";
    }
};

int main() {
    Base *p = new D;
    p->VeryLongFunctionName(0);
            // the intention is to print D::. But it prints C::.
            // How can we make compiler catch it.       
    return 0;
}
like image 879
Andrei Avatar asked Mar 21 '11 06:03

Andrei


2 Answers

not exactly what you asked for, but i've used this form to reduce the chance for human error:

class t_very_long_argument_list {
public:
    t_very_long_argument_list(T1& argument1, const T2& argument2);
    /* ... */
    T1& argument1;
    const T2& argument2;
};

int C::VeryLongFunctionName(t_very_long_argument_list& arguments) {
    std::cout << "C::\n";
}
like image 63
justin Avatar answered Oct 01 '22 13:10

justin


For this exact purpose C++0x introduces the override member function decorator, as is already implemented in VC++ 2005 and later: http://msdn.microsoft.com/en-us/library/41w3sh1c.aspx

Alternatively, VC++ permits the following (presumably compiler-specific):

#include <iostream>

class Base {
public:
    virtual void VeryLongFunctionName(int VeryLongArgumentList) = 0;
};

class C : public Base {
public:
    void Base::VeryLongFunctionName(int VeryLongArgumentList) {
        std::cout << "C::\n";
    }
};

class D : public C {
public:
    void Base::VeryLongFunctionNane(int VeryLongArgumentList) {
    //   ^^^^^^ now causes a compilation error
        std::cout << "D::\n";
    }
};
like image 35
ildjarn Avatar answered Oct 01 '22 13:10

ildjarn