Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can member function arguments be of the same class type?

Tags:

c++

class

//node.h 
class node 
{
      public:
            void sort(node n);

};

I didn't try the code yet . But It's interesting to know if is this a valid case and Why ?

Edit :

This leads me to another question : Can I declare FOO inside a member function like this ?

//FOO.h
Class FOO
{
   public:
   void sort(int n) ;
   void swap(int x , int y ); 
}

//FOO.cpp

void FOO::sort (int n)
{
     FOO obj;
     obj.swap(3 , 5) ;
}
like image 946
Ahmed Avatar asked Nov 21 '25 17:11

Ahmed


1 Answers

Yes, that's perfectly valid. If you couldn't do that, how could you write copy constructors?

A similar, but not valid case, is including the same type as a member of your class/struct.

struct Foo
{
  Foo m_foo;
};

You can't do that, because it's essentially a circular definition, and if you had:

struct Foo
{
  Foo m_foo;
  Foo m_bar;
};

Then a Foo would be 2 Foos, which would be 4 Foos, which would be 8 Foos etc. which makes no sense.

You can, on the other hand, have pointers to the same type:

struct Foo
{
  Foo* m_foo;
};

Because a pointer to Foo isn't the same as Foo. A pointer is a pointer, no matter what it points to, so there is no circular definition or dependencies.

like image 92
Peter Alexander Avatar answered Nov 23 '25 07:11

Peter Alexander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!