user8560436
user8560436

Reputation:

Cpp define in classes

I started C++ programming few weaks ago and i have a question about defining the file of a class in a separate file. This is my code.

main.cpp

#include <iostream>
#include "Maths.h"
int main() {
  Maths m;
  int s = m.sum(1,2);
  std::cout << s << std::endl;
  return 0;
}

Maths.h

#ifndef Maths_H
#define Maths_H

class Maths
{
  public:
    int sum(int a, int b);
};

#endif

Maths.cpp

#include <iostream>
#include "Maths.h"
int Maths::sum(int a, int b)
{
  return a + b;
}

Why is it that you can't #define the same name as your class name. For example in my script Maths? https://repl.it/repls/UnwillingFreeHeterodontosaurus

Upvotes: 1

Views: 3668

Answers (2)

Arrrow
Arrrow

Reputation: 542

Macros have the compiler replace the text with a defined value. So if for instance you have this macro:

#define Math

It will replace all the "Math" occurences with nothing, since you didn't define a value to replace it. Defining it like:

#define Math 1

Will replace all occurences of "Math" with the value 1.

As for having to include the base class: The compiler has to know where to find the base class. If you don't include the header containing the base class, the header of the derived class has no way to know where to get the base class from, so it will give a Undefined reference to ... error.

You should also place the include guards above any other code. So not like this:

#include "Enemy.h"
#ifndef Ninja_H
#define Ninja_H
//...
#endif

But like this:

#ifndef Ninja_H
#define Ninja_H
#include "Enemy.h"
//...
#endif

The include guards are basically there to tell the compiler that it's already parsed that file. If you place code outside of the guards it will likely cause errors. Placing an include like that will disable certain optimisations, which in turn leads to longer compile time. Simply put: there is no benefit placing it like that.

Upvotes: 1

Some programmer dude
Some programmer dude

Reputation: 409166

What you #define is called a macro, and the preprocessor replaces the macros with something.

For example, you define the macro Maths to be replaced by nothing, and that's what the preprocessor will do. The definition class Maths { ... } will be replaced by class { ... }. Which is not valid.

Since preprocessor macros doesn't live in any specific namespace (they really handled separately from the actual C++ parser) they are global. And to avoid clashes in symbol names, macros are usually spelled with all upper-case letter. In your case you should use MATHS instead.

Upvotes: 1

Related Questions