Why can't members and methods have the same name?

Discussion in 'C++' started by cppaddict, Jun 11, 2004.

  1. cppaddict

    cppaddict Guest

    Hi,

    The following class containing a member and a method with the same
    name will not compile:

    class Test {
    private:
    bool x;
    public:
    Test() : x(true) {};
    bool x() const {return x;}
    };

    I am not advocating writing code like the above, but I was puzzled by
    the compiler's reason for rejecting it: It said there were multiple
    declarations of Test::x.

    Since methods and members can always be distinguished syntactically
    when they are used, it seems strange that they cannot have the same
    name. Just curious why this is?

    thanks for any explanations,
    cpp
     
    cppaddict, Jun 11, 2004
    #1
    1. Advertisements

  2. cppaddict

    JKop Guest

    cppaddict posted:

    int morang(int prot);

    int main(void)
    {
    int (*pMorang)(int) = morang;
    }



    When you write a function's name without parenthesis, you've got a pointer
    to the function.


    -JKop
     
    JKop, Jun 11, 2004
    #2
    1. Advertisements

  3. Are they? Take a look:

    struct Functor {
    void operator() { 42; }
    };

    struct Test {
    Functor x;
    void x() {}
    };

    int main() {
    Test t;
    t.x();
    }

    Now, when I do 't.x()', is that invoking the member _function_ x,
    or is it calling the operator() of the _data_ member x?

    V
     
    Victor Bazarov, Jun 11, 2004
    #3
  4. Are you sure they can always be distiguished syntactically? Please
    consider the example below. What should its output be?


    #include <iostream>

    int foo ()
    {
    return 1;
    }

    class Test {
    public:
    Test () : x (foo) {}
    int (*x) ();
    int x () const { return 2; }
    };

    int main ()
    {
    Test t;
    std::cout << t.x () << '\n';
    }


    Martin
     
    Martin Dickopp, Jun 11, 2004
    #4
  5. cppaddict

    cppaddict Guest

    Ah yes. Of course.

    Thanks,
    cpp
     
    cppaddict, Jun 11, 2004
    #5
  6. cppaddict

    Bill Seurer Guest

    &Test::x

    which x is it?
     
    Bill Seurer, Jun 11, 2004
    #6
  7. They can't always be distinguished.

    class F {
    public:
    void operator () () { }
    };

    class Test {
    F f;
    void f ();
    public:
    Test ()
    {
    f (); // What f ?
    }
    };
     
    =?ISO-8859-15?Q?Juli=E1n?= Albo, Jun 11, 2004
    #7
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.