Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "char fun[](int x) const" do?: C++ Syntax Error

Tags:

c++

syntax

I am following along with a video emulating a cpu in C++. The programmer used the following and it is the first time I encounter it:

This is the code from the video:

struct Mem
{
    Byte Data[MAX_MEM];

    Byte operator[]( u32 Offset ) // <-- I don't understand this syntax
    {
    }
}

I wrote it in my own project like this:

char data[1024*64];
char fun[] ( int x ) const  // <-- Is this right?
{
  return data[x];
}

my issue is with line 1# of the example. They were able to compile but I am met with errors:

incomplete type is not allowed;
array of functions is not allowed;
a type qualifier is not allowed on a nonmember function.

What does this syntax actually do; is there an alternative way to write it?

like image 232
Maeximilian Avatar asked May 07 '26 12:05

Maeximilian


1 Answers

Your minimal example isn't quite right; the syntax they are using in the video is very particular and you've changed some crucial pieces - they are overloading the indexing operator as a member of a class. A silly minimal example of what's going on is as follows:

struct X {
   char data[1024];
   char& operator[](int index) {
      return data[index];
   }
};

where you could later write code such as

X x;
x[5] = 'a';

where the snippet x[5] will invoke your user defined operator[] passing 5 as an argument. The important point here is that, essentially, the name of the function in the class is operator[] - and that that's just some special name related to C++'s feature of operator overloading. There's some fixed set of other operators that can be defined this way - you'll also see operator() is you want x(a,b,c,...) to be defined for an object of user-defined type X or operator+ if you want x+y to be defined. Note that operator is a keyword - its name is not interchangeable with others. Also, for the indexing operator (and a few others), such functions may only be defined within classes (though some, such as operator+ can be defined outside of classes).

There's a good general reference on overloading over at this question.

like image 142
Milo Brandt Avatar answered May 09 '26 02:05

Milo Brandt



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!