Creating a static field in header file | C++ - c++

I am working on an assignment, and while I don't have any issues with the actual assignment, I want to make my code "proper." I am trying to define a static variable in my header file. I want it to be static so that all instances of this class can access the same variable. I don't want to extern it either, I want just this class to have access to it.Then I am trying to define it in the actual file (not header) but I keep getting an error about not being able to cast. I just want to learn how to properly do this to have cleaner code.

The definition of your field stays inside the class:
class AddrSpace
{
List *availSpots;
};
The full name of this variable will be AddrSpace::availSpots. C++ requires to define static variables (including the static fields of the classes) explicitly. I would not say this is fully logical because compiler already has everything to generate all necessary stuffs. Nevertheless this is so. The definition in your C++ file should look like:
List *AddrSpace::availSpots = new List();
Next time please add the source directly into the question.

Related

Creating a new c++ object from within a lua script?

---Context---
I want to have a class called "fileProcessor". This class is completely static and merely serves as a convinient namespace (within my normal library namespace) for some global function. This is a basic blueprint of the class with only the relevant stuff
class fileProcessor{
private:
lua_State* LUA_state;
public:
static std::variant<type1,type2> processFile(const char* filePath,const char* processorScript);
}
Please note again that I ommitted most of the stuff from the class so if anything seems odd ignore it.
What process file is supposed to do is:
Read the filePath file, storing all directives including it (this is my own filetype or style of syntax. This is already handeled correctly). The directives are stored with strings, one for the command and one for everything after it.
Read the script file and check if it has a commented out fileProcessor line at the top. This is to make sure that the lua script loaded is relevant and not some random behaviour script
Load and compile the lua script.
Make all read directives available (they are saved in a struct of 2 strings as mentioned before)
Run the file and recieve a object back. The object should only be of types that I listed in the return type (variant)
I am having problems with step 4 and one vital part of the scripting.
---Question---
How can I make the creation of a full new object of type1 or type2 possible within lua, write to it from within lua and then get it back from the lua stack into c++ and still know if its type1 or type2?
---No example provided since this question is more general and the only reason I provided my class is for context.---
It seems like you are trying to do it the other way around. I quote a part of this answer:
...you are expecting Lua to be the primary language, and C++ to be the client. The problem is, that the Lua C interface is not designed to work like that, Lua is meant to be the client, and all the hard work is meant to be written in C so that Lua can call it effortlessly.
If you are convinced there is no other way that doing it other way around you can follow the workaround that answer has given. Otherwise I think you can achieve what you need by using LUA as it meant to be.
LUA has 8 basic types (nil, boolean, number, string, userdata, function, thread, and table). But you can add new types as you require by creating a class as the new type in native C++ and registering it with LUA.
You can register by either:
Using some LUA helper for C++ like luna.h (as shown in this tutorial).
Pushing a new lua table with the C++ class (check this answer).
Class object instance is created in your native C++ code and passed to LUA. LUA then makes use of the methods given by the class interface.

C++ Declaration of class variables in header or .cpp?

So far, I've been using classes the following way:
GameEngine.h declares the class as follows
class GameEngine {
public:
// Declaration of constructor and public methods
private:
InputManager inputManager;
int a, b, c;
// Declaration of private methods
};
My GameEngine.cpp files then just implement the methods
#include "____.h"
GameEngine::GameEngine() {
}
void GameEngine::run() {
// stuff
}
However, I've recently read that variable declarations are not supposed to be in the header file. In the above example, that would be an inputManager and a, b, c.
Now, I've been searching for where to put the variable declarations, the closest answer I found was this: Variable declaration in a header file
However, I'm not sure if the use of extern would make sense here; I just declare private variables that will only be used in an instance of the class itself. Are my variable declarations in the header files fine? Or should I put them elsewhere? If I should put them in the cpp file, do they go directly under the #include?
Don't confuse a type's members with variables. A class/struct definition is merely describing what constitutes a type, without actually declaring the existence of any variables, anything to be constructed on memory, anything addressable.
In the traditional sense, modern class design practices recommend you pretend they are "black boxes": stuff goes in, they can perform certain tasks, maybe output some other info. We do this with class methods all the time, briefly describing their signature on the .h/.hpp/.hxx file and hiding the implementation details in the .cpp/.cc/.cxx file.
While the same philosophy can be applied to members, the current state of C++, how translation units are compiled individually make this way harder to implement. There's certainly nothing "out of the box" that helps you here. The basic, fundamental problem is that for almost anything to use your class, it kind of needs to know the size in bytes, and this is something constrained by the member fields and the order of declaration. Even if they're private and nothing outside the scope of the type should be able to manipulate them, they still need to briefly know what they are.
If you actually want to hide this information to outsiders, certain idioms such as PImpl and inlined PImpl can help. But I'd recommend you don't go this way unless you're actually:
Writing a library with a semi-stable ABI, even if you make tons of changes.
Need to hide non-portable, platform-specific code.
Need to reduce pre-processor times due to an abundance of includes.
Need to reduce compile times directly impacted by this exposure of information.
What the guideline is actually talking about is to never declare global variables in headers. Any translation unit that takes advantage of your header, even if indirectly, will end up declaring its own global variable as per header instructions. Everything will compile just fine when examined individually, but the linker will complain that you have more than one definition for the same thing (which is a big no-no in C++)
If you need to reserve memory / construct something and bind it to a variable's name, always try to make that happen in the source file(s).
Class member variables must be declared in the class definition, which is usually in a header file. This should be done without any extern keywords, completely normally, like you have been doing so far.
Only variables that are not class members and that need to be declared in a header file should be declared extern.
As a general rule:
Variables that are to be used with many functions in the same class go in the class declaration.
Temporary variables for individual functions go in the functions themselves.
It seems that InputManager inputManager; belongs in the class header.
int a, b, c; is harder to know from here. What are they used for? They look like temporary variables that would be better off in the function(s) they're used in, but I can't say for sure without proper context.
extern has no use here.

Class with no data members in C++

This may not be a question specific to C++ and more to do with Object oriented programming. I am new to this and I am doubtful of my design. I have a class Parser that basically implements many functions dealing parsing expressions, conversion from infix to postfix etc. I use these Parser functions in the main function. I realized that I do not need any data members for this class. Hence, I do not really need an object of this class. Hence, I ended up making every function static in the class. Is there something strange about this design. Should I have this as an interface instead? Any suggestions?
You want a parser and you know what you want it to do for you - this is in effect, your "interface".
Your current implementation of the parser doesn't need any member variables - therefore, to implement your interface, you don't need a class. So yes, do away with your static methods. Like Kevin says, using a namespace with plain old functions (non-static) is a great idea.
If you feel you will need to add a new parser that WILL need to maintain internal state, then you probably want to define an interface in (1) - a plain old publicly visible header file with function declarations inside a namespace of your choice is enough.
A class with nothing but static functions seems pretty indistinguishable from a namespace to me. So, why not just use a namespace?
The way to decide for this question is on how will the functions be used?
1) If all the functions are used in one file and do not need to be exported anywhere, then definitely use static functions. Why? Because you can just type them directly into the body of the class in the .cpp file and you do not have to worry about maintaining declarations and keeping parameters aligned. Because when a C++ class is parsed all the code inside each function defined inside the class body is skipped and then parsed once all the classes members have been declared, so the functions can all see each other and are in a better name situation.The compiler will also inline a lot of the smaller functions if you declare them directly in the class like that.
2) If the functions need to be used from outside the current .cpp file, then use normal functions. Because later they can be used from anywhere else and exporting them by name is easier.
It is common to make utility functions static, so, if the functions of your Parser class do not rely on each other, you totally can made them static. If they rely on each other, and it may be possible that the same functions can be done another way, you should consider to use an interface

Member function definition

What is the right approach to take:
Define the member (class) function inside the class?
Define the member (class) function outside the class?
Thanks.
Assuming you're talking about these three possibilities:
Method defined in class definition in header file.
Method define outside class definition in header file.
Method define outside class definition in implementation file.
Then project and company guidelines may force you to use (1) or (3) always.
When you have a choice, it's IMHO best to adapt to circumstances at hand, considering things such as
Do you want a header-only module? Then (1) as default, (2) possible.
Is the method a large beast? Then (2) or (3).
Template method specialization? Then (2) or (3).
There is a build-time problem (slow builds)? Indicates (3).
Template class? (1) or possibly (2)
But except where the choice is effectively forced on you, above all consider the clarity of your code.
Cheers & hth.,
A common advice is to keep headers as simple and clean as possible. Headers will be included by external code, and they will have to process everything that you have written there. If you write a method in the header, all translation units will compile that function, only so that the linker can discard all but one of them later on.
If your code has an internal dependency on a type or library that is not part of your interface, then by inlining the code of the member function in the class declaration the definition of that class or the headers of that library will have to be included in your header, and that means that you are leaking your implementation details to your users.
Unless the member function definition is trivial (in an informal sense) and doesn't introduce any additional dependencies I would normally define a member function outside of the class body in a separate source file.
It's often a matter of style but there are some cases in which it is necessary and many other cases in which it is desirable to define function outside of the class body.
For example, in the cases where you have interdependent classes and only a forward declaration of another class can be made available before the class definition, a member function which uses the definition of that other class can only be defined outside of the class body after a full definition of the other class has been provided.
Do you mean "in the class declaration / .h file" vs "in a .cpp file using ::" ?
If so I always go for the latter. When it comes to debugging, it's a lot easier to step through and see what's going on. It also helps declutter the class declaration, which doesn't need to know any implementation details"
If you want to define a function within a class the most basic syntax looks generally like:
class Object
{
int property;
void doSomething()
{
property=100;
}
};
If you want to define a function outside it is similar to declaring functions before main and in library files. In your class you have:
class Object
{
int property;
void doSomething();
};
Then somewhere after your class, after the main() function or in an included file you can have the definition:
void Object::doSomething()
{
property=100;
}
Some place classes in a header file and the definitions in a cpp file used by that header. Various techniques possible.
Both of these approaches are valid. Often I will include very small and/or core class functionality directly within the class and other functions which do heavier bulk work I tend to separate. Try to think the difference in coming upon your code and wanting to alter it.
if we see according to performance issue than it is more effective way to declare the function in the class . becouse at the compile time it conects all the funcation calls and other components so it will easy and must be faster to get all in one source...

Adding static member variable to third-party class

I'm using Boost.Property_Tree for a project and I want to add a small bit of functionality to it. I want to add a "fromFile" static member variable that will figure out the file type and then use the proper parser. In my project, this is currently how I've got it.
typedef boost::property_tree::ptree ConfigNode;
Then I have another class called ConfigLoader that I've been using to load the file. I want to add the one function to a ConfigNode class though. I need the compiler to treat ConfigNode as if it were a boost::property_tree, but I want to add one static function. Is there a way to do this?
Nope. There's no clean way to do this.
You have two options:
Declare your functions and variables outside of the class completely (e.g. in another class or global in some namespace).
Subclass boost::property_tree, adding your static member(s).