Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

If you're worried about these things (I am not), simply restrict the private method to be called only from other class methods. Wait, that's how private methods work already...


Ok I admit to feeling a bit stupid now - you're absolutely right of course. On that basis I don't see why it should be necessary to declare private method signatures inside the class definition at all. I can't really see any reason it shouldn't simply be allowed to define (non-virtual) private class methods anywhere you like - as you say, if someone else other than the original class-author does so, they wouldn't be able to call the function anyway!

So what is a good justification for the current language design? I did find one SO post suggesting if your suggestion were possible, the overloading rules would probably have to change, but that doesn't seem like an insurmountable hurdle.

To be clear, what you're suggesting is that header file (foo.h/hxx/hpp) would have:

    class Foo {
        public:
            Foo();
            void doYourThing();
        private:
            int _privInt;
            std::string _privStr;
    }
then foo.cxx/cpp would have something like:

    /*private*/ Foo::ctorHelper() {
        _privInt = 42;
    }

    Foo::Foo() { ctorHelper(); }
 
    /*private*/ bool Foo::anotherHelper() {
        return _privStr.find("bar") != std::string::npos;
    }

    void Foo::doYourThing() {
        if (anotherHelper()) {
           std::cout << "The foo thing\n";
        }
    }
Whether or not some sort of keyword is needed to mark the private functions as such is stylistic I suppose - I'd prefer it were there, but I'm used to C# where the access specifier is part of every member declaration anyway. But it's certainly not necessary - the compiler would just assume "private" if the declaration is not part of the class definition. And yes, someone else could come along and put

     void Foo::anotherPrivateFunction() {
     }
in their own code, but they'd never be able to call it anyway, so no harm done (arguably compiler could treat an "unreferenced" private function as an error in itself, but certainly the linker would just strip it out).

Obviously one downside of the above is that if you wanted friend classes to be able to call such private methods, they'd either have to forward declare them, or you'd put them into a separate "foo_private" header file, but again, I'm not seeing why that's a big problem.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: