0

Is it legal in func1 and func2? Class methd contains the same class object.

example:

class Foo
{
public:
    void func1() {
        //...
        Foo foo; // Is it legal?
        //...
    }

    // Is it legal in paramete?
    void func2(Foo object) {
        //...
    }

    // It is legal using reference
    // http://stackoverflow.com/questions/6921185/why-do-objects-of-the-same-class-have-access-to-each-others-private-data
    void func3(Foo& object) {
        //
    }
};
Jcppython
  • 179
  • 12
  • 6
    Why don't you compile it and find out? –  May 18 '17 at 09:59
  • @InternetAussie I have actual codes. It can be compiled but have some segment fault. – Jcppython May 18 '17 at 10:00
  • @InternetAussie, possibly for the usual reason that many compilers support non-standard extensions *by default*, without warning that your program is not conformant. – Toby Speight May 18 '17 at 11:57

5 Answers5

4

Is it legal?

yes

Why?

class Foo
{
public:
    void func1() {
        //...
        Foo foo; // Is it legal?
        //...
    }
};

The body of a class member function is compiled after the entire class definition has been considered.

For this reason, the entire class is available to the method's implementation, including methods and members declared after the current method.

This is covered in [class.mem]

Within the class member-specification, the class is regarded as complete within function bodies, default arguments, using-declarations introducing inheriting constructors, exception-specifications, and brace-or-equal-initializers for non-static data members (including such things in nested classes).

Richard Hodges
  • 68,278
  • 7
  • 90
  • 142
2

Yes, it is legal in all of your cases.

But it is illegal in constructor of copy:

// here should be 'const Foo&'
Foo(const Foo object);
knst
  • 523
  • 2
  • 16
1

Sloppy speaking, the only difference between a free function and a member function is that a member function get a this passed as first argument (you dont see it explicitly but it is there). This is not completely true, but true enough to understand that there is no reason not to have a Foo inside a member function of Foo.

What you cannot do is something like this:

struct Bar {
    Bar x;
};

thats not only a quite strange construct ("its turtles all the way down", just in case you know that quote) but also your complier will clearly tell you that it cannot work.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
0

Yes, it is legal in all of those three cases.

syntagma
  • 23,346
  • 16
  • 78
  • 134
0

of course it is 100% legal, that is what many operators need as parameter, and many other functions use...

look this example taken from the String class:

string& operator+= (const string& str);

so string class has a function taking another string as parameter...

ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97