0

I'm learning c++ and was playing around with macros. I tried defining push_back as pub, and it gave me this error:

error: reference to non-static member function must be called
  vect.pub(1);

Here's my code:

#include <vector>

using namespace std;
typedef vector<int> vi;
#define pub push_back;

int main(){
  vi vect;
  vect.pub(1);
}

When I didn't use the #define and just wrote push_back, there was no error messages.

What exactly changed when I used the macro?

Geno C
  • 1,401
  • 3
  • 11
  • 26
feverdreme
  • 467
  • 4
  • 12

3 Answers3

2

You should not put ';' for macro.

 #include <vector>

 using namespace std;
 typedef vector<int> vi;
 #define pub push_back

 int main(){
   vi vect;
   vect.pub(1);
 }
Farhad Sarvari
  • 1,051
  • 7
  • 13
2
#define pub push_back;

//...

vect.pub(1);

This expands to the following, which is invalid syntax due to the extra ;.

vect.push_back;(1);

So drop the ; and #define pub push_back.

dxiv
  • 16,984
  • 2
  • 27
  • 49
0

I'm learning c++ and was playing around with macros.

Stop. push_back is at most 6 extra keystrokes. Code is meant to be read by humans. You can't find pub in documentation, but you can find push_back.

Similarly using namespace std; is a terrible habit. There are loads of names that you don't realise you've just imported into the global namespace there.

Caleth
  • 52,200
  • 2
  • 44
  • 75
  • I was learning c++11 for competitive programming. *Any* time shaven is good and this code is only meant to be readable by me – feverdreme Jan 13 '21 at 04:25