1

I want to create a member function with the same name of the returning type. Example:

class A { };

class B {
public:
    A& A() { return *a; }
private:
    A* a;
};

However, the compiler won't let me. I tried to change the type of the member return type to ::A (as sugested here, but with no avail. I know I could just change the member name, but I just want to understand why does it has this restriction, and what are my workarounds.

Community
  • 1
  • 1
André Wagner
  • 1,330
  • 15
  • 26

2 Answers2

2

If you declare a member called A you can no longer use the type A without an explicit namespace. You need to change every occurrence of the type A to ::A.

The corrected code looks like:

class A { };

class B {
    public:
        ::A& A() { return *a; }
    private:
        ::A* a;
};

Fixed code on codepad:

http://codepad.org/cilF9rKm

bikeshedder
  • 7,337
  • 1
  • 23
  • 29
0

That's because a member with the same name as the class is a constructor. However, you try to declare one with a type, which is an error. You can only define constructors the way the language wants you too (without an explicit return type).

For example, if you had a method in B that said

A x = A();

it is ambiguous whether you are calling B::A() or are constructing a new A object.

Raymond Chen
  • 44,448
  • 11
  • 96
  • 135
Linuxios
  • 34,849
  • 13
  • 91
  • 116
  • 1
    The member has a different name and is not a constructor. The class is called `A` and the member is called `B`. – bikeshedder Feb 02 '13 at 17:36