creating an array of objects within a function of a program - c++

could someone please tell me what I need to do in order to create an array of objects in a function (other than in the main function).
I will try to explain by making up some sort of example...
Let's say I have a program named TimeScheduler.cpp that implements the class Schedule.h
(and I have the implementation in a separate file Schedule.cpp where we define the methods).
In the declaration file we have declared two constructors
Schedule(); //the default
and
Schedule(int, int, int);//accepts three arguments
to get to the point--let's say in the main program file TimeScheduler.cpp we created our own functions in this program apart from the functions inherited from the class Schedule. so we have our prototypes listed at the top.
/*prototypes*/
void makeSomeTime();
etc.....
we have
main(){
//etc etc...
}
we then define these program functions
void makeSomeTime(){
//process
}
let's say that inside the function makeSomeTime(), we would like to create an array of Schedule objects like this
Schedule ob[]={
summer(5,14, 49),
fall(9,25,50)
};
what do I have to do to the function makeSomeTime() in order for it to allow me to create this array of objects.
The reason I ask is currently i'm having difficulty with my own program in that it WILL allow me to create this array of objects in main()....but NOT in a function like I just gave an example of. The strange thing is it will allow me to create a dynamic array of objects in the function..... like
Schedule *ob = new Schedule[n+1];
ob[2]= Schedule(x,y,z);
Why would it let me assign to a non-dynamic array in main(), but not let me do that in the function?

This is not correct:
Schedule ob[]={
summer(5,14, 49),
fall(9,25,50)
};
You appear to be trying to introduce 3 new names:
ob, which is an array of Scedules
summer, which is a Schedule
fall, which is a Schedule
You can't introduce summer and fall as new names like that. Perhaps this was just a typo, and you meant:
Schedule ob[]={
Schedule(5,14, 49),
Schedule(9,25,50)
};
...which is perfectly fine, and can exist in a function such as:
void make_schedule()
{
Schedule ob[]={
Schedule(5,14, 49),
Schedule(9,25,50)
};
}
But now you have another problem -- your make_schedule function returns void. The Schedule array you created in make_schedule is created and then just thrown away. If you want to return an array from a functtion, the best thing to do is to use a vector, and return that:
std::vector<Schedule> make_schedule()
{
Schedule ob[]={
Schedule(5,14, 49),
Schedule(9,25,50)
};
const size_t num_obs = sizeof(ob)/sizeof(ob[0]);
std::vector<Schedule> ret;
std::copy( &ob[0], &ob[num_obs], std::back_inserter(ret));
return ret;
}
A poorer alternative is to use dynamic allocation to allocate your array, and return a pointer to the first element. In this case, when using new [] it's important to note that you can only use the default constructor.

I decided that instead of using a vector, I could use an unordered_map. I didn't realize that when you 'name' an object in c++, you aren't really giving it a name...it is simply used as a sort of temporary reference. if you want to use names you are better off using a name as a sort of key value in a set. like:
string foodname;
foodname = "cake";
[foodname, 10.95]
foodname = "bread";
[foodname, 5.75]
I found help with unordered_map on http://msdn.microsoft.com/en-us/library/bb981993.aspx

Related

Convert data type a of class object (C++)

I am writing a game in which one Object has an ability to turn into an object of another class (e.g. Clark Kent -> Superman). I would like to know what is the most efficient way to implement this.
The logic of my current code:
I have created a turnInto() function inside the ClarkKent class. The turnInto function calls the constructor of Superman class, passing all needed infos to it. The next step is to assign the address of Superman object to the current ClarkKent object.
void ClarkKent::turnInto() {
Superman sMan(getName(), getMaxHP(), getDamage());
&(*this) = &w; // <- error here
this->ClarkKent::~ClarkKent();
}
As you might have guessed, the compiler gives an error that the expression is not assignable. Not sure how to find a correct solution to this.
Keep it simple and don't play tricks you don't understand with your objects.
Superman ClartkKent::turnInto() {
return {getName(), getMaxHP(), getDamage()};
}
At the callee:
ClartkKent some_guy{...};
auto some_other_guy = some_guy.tunInto();
Or if you need something fancy:
using NotBatman = std::variant<ClartkKent, Superman>;
NotBatman some_guy = ClartkKent{...};
using std::swap;
swap(some_guy, some_guy.tunInto());
IDK

C++ class filler syntax error

My class is as follows:
class stats {
public: int strength,
perception,endurance,charisma,inteligence,agility,luck,health,stamina,mana,karma;
};
As far as I know, there shouldn't be anything wrong with it, unless I need to set up a constructor and destructor.
I create my object using the following line:
stats* mainstat=new stats;
And I have the following function to "fill" objects of the said class:
void statfiller(stats* object, int table[]){
object->strength=table[0]; object->perception=table[1];
object->endurance=table[2]; object->charisma=table[3];
object->inteligence=table[4]; object->agility=table[5];
object->luck=table[6]; object->health=table[7];
object->stamina=table[8]; object->mana=table[9];
object->karma=table[10];
}
So, until then, no problem. At least, until the following:
I create a table with the data to fill, then feed it to my fill function.
int tablet[10]; tablet[0]=5; tablet[1]=5; tablet[2]=5; tablet[3]=5;
tablet[4]=5; tablet[5]=5; tablet[6]=5; tablet[7]=50; tablet[8]=50;
tablet[9]=50; tablet[10]=0;
statfiller(mainstat*,tablet);
When I do this, a compiling error comes up, stating the syntax of my function is incorrect.
Why is it so? Do I need to use pointer(*) or address(&)? Is there something I'm missing?
Odds are, the solution is very simple, but at the moment of typing this, I just don't see what's wrong with it ^^;
Solution to this problem was the following:
The function's syntax is "void statfiller(stats* object, int table[]) ", where the stats* object serves as reference, pointer to an object of stats class.
In the function's call "statfiller(mainstat*,tablet);", the mistake I made was calling a pointer of a stat object (in this case mainstat) instead of just putting in the object.

C++ Create objects in a try bloc then store them in a std::array

I have a Player object which can throw an exception inside its constructor, so in my main function I'm creating 2 Player objects inside a try block.
I want to store these 2 Players in a std::array like that:
try
{
Player p1(10, 10, ikazuchi);
Player p2(70, 10, hibiki);
std::array<Player, 2> players = {p1, p2};
}
The problem is that I wouldn't be able to use the array outside of the try block, and I heard that placing all the main code inside a try block is often a bad idea.
I can't declare my std::array after the try block because p1 and p2 no longer exist there.
I can solve the problem with a std::vector, but I have read that it was better to use a std::array when I know the size of the array during the compilation.
I could create a default constructor to create my objects then fill them inside the try block, but it seems to be more proper to create everything in the constructor.
What would be the best practice for that?
You can always get around issues like this using dynamic allocation or something like boost::optional<std::array<Player, 2>>, but the real question is: should you? That is, assume one of the player objects fails to construct and throws an exception. What will you do with the players array after that? It's not in a legal state, or at least not in the state you'd expect it to be if no exception was thrown.
There is no problem with having the scope of a try be large. It should cover everything where an exception will prevent you from progressing. If you don't like physically having a lot of source code there, move the code into a function. This might be a good idea anyway: one function which assumes all goes well, and another one whose chief responsibility is to handle errors.
And if you have meaningful ways of continuing to use players when the objects inside are in an invalid state (constructor threw), then you can just create the array with objects in that state in the first place (outside the try block), and just assign them inside the try.
The question states you don't want to provide an unneeded default constructor, but I claim that either player belongs inside the try, or Player needs a default constructor (or an equivalent way of expressing "not initialised properly).
You can do something like below.
int main() {
std::array<int, 2> array;
try {
array[0]=1;
array[1]=1;
} catch (...) {
}
return 0;
}
Use Player instead of int;
If your players csn be copied/moved and trivially constructed, just create the array and assign into it.
std::array<Player, 2> players;
try{
players[0]=Player(10, 10, ikazuchi);
players[1]=Player(70, 10, hibiki);
} catch ...
alternatively you can do:
std::optional<std::array<Player, 2>> players;
try{
Player p1(10, 10, ikazuchi);
Player p2(70, 10, hibiki);
players.emplace(std::array<Player, 2>{{std::move(p1),std::move(p2)}});
} catch ...
but you may need to find a non-C++17 version of optional, like boost optional.
Another approach is:
auto players = [&]()->std::array<Player, 2>{
try {
Player p1(10, 10, ikazuchi);
Player p2(70, 10, hibiki);
return {{std::move(p1),std::move(p2)}};
} catch (some_error){
throw some_other_error;
}
}();
but thus requires exit either by array or by throw.

C++, how to call functions when reading their ID number from a Mysql table?

I have a Mysql table that I am using as a list of different calculations that needs to be done.
Each line in the table has a column of type INT that has the number of the function that needs to be called.
e.g. line 6, data, (function) 1.
I read all the lines one by one and I need to call the relevant functions for each line.
What is the best way to construct it in C++?
should I have another function that returns the pointer of the functions that needs to be called ?
Are there other recommended solutions?
Thanks
It depends on the type of the function (input/outputs) but assuming they are all the same, you can make an array of function pointers. For example:
std::vector<void(*)(int)> MyArray;
Will declare an array of function pointers returning void and taking one int as parameter. Then you can put the functions you want in it and when you want to call them you can use MyArray[i]
If the actual type for the function pointer is long and hard to type, you can use decltype(MyFunction) instead. This requires C++11 though.
Using function pointers may work may work but I would rather make use of something like Strategy pattern.
class DataProcessor {
public:
virtual void process(Data& data) = 0;
// some other things like dtors etc
}
For each type of "function" you can create its corresponding DataProcessor.
To ease lookup, you may make use of a factory, or simply a std::map<int, DataProcessor> (instead of using int as key, will you consider using an enum?), or even a vector/array of DataProcessor.
As a suggestion, this is another way:
//Create only a function and make a switch statement in it:
void myfunction (std::pair<int,int> aRow) { // function:
int result;
int data = aRow.second;
int function_id = aRow.second;
switch(function_id){
case 1:{
//Funcion with any signature
break;
}
case 2:{
//Funcion with another signature
break;
}
//and so on...
}
//do something with the result...
}
int main () {
//Fetch your mysql data here:
std::vector<std::pair<int, int> > myMySQLdata;
for_each (myMySQLdata.begin(), myMySQLdata.end(), myfunction);
}

Using functions from classes

I am learning C++ and very new at using classes, and I am getting very confused in trying to use them. I am trying to convert my existing code (which used structs) so that it uses classes - so while I know what I am trying to do I don't know if I'm doing it correctly.
I was told that when using functions from the class, I first need to instantiate an object of the class. So what I have tried (a snippet) in my main function is:
int main()// line 1
{
string message_fr_client = "test"; //line2
msgInfo message_processed; //line 3
message_processed.incMsgClass(message_fr_client); //line 4
if (!message_processed.priority_check(qos_levels, message_processed)) //line 5
cout << "failure: priority level out of bounds\n"; //line 6
return 0; //line 7
}
Could you help me clarify if my following assumptions are correct? The compiler is not showing any error and so I don't know if it is error-free, or if there are ones lurking beneath.
At line 4, is the function incMsgClass being performed on the string message_fr_client and returning the resultant (and modified) message_processed?
At line 5, the function priority_check is being performed on the message_processed and returning a boolean?
In my class definition, I have a function getPath that is meant to modify the value of nodePath - is it just a matter of using message_processed.getPath(/*arguments*/)?
I haven't included the body of the functions because I know they work - I would just like to find out how the class functions interact. Please let me know if I can be clearer - just trying to clear up some confusion here.
Here is my class:
#ifndef clientMsgHandling_H
#define clientMsgHandling_H
#include <list>
#include <map>
#include <queue>
class msgInfo
{
public:
msgInfo();
msgInfo(int, int, int, std::string, std::list<int>);
/*classifying message*/
msgInfo incMsgClass(std::string original_msg);
/*message error checks*/
bool priority_check(int syst_priority, msgInfo msg); //check that message is within qos levels
bool route_check(std::map<std::pair<int, int>, int> route_table, msgInfo msg); //check that route exists
void getPath(msgInfo msg, std::map<std::pair<int, int>, int> route_info, int max_hop);
private:
int source_id;
int dest_id;
int priority;
std::string payload;
std::list<int> nodePath;
};
#endif
While it may compile (and even run), there are a few oddities with the code as shown:-
First off, class methods know which object they are operating on - so your priority_check and route_check methods probably don't need msgInfo as a parameter.,
for example, your old non-class function might be like this
bool priority_check(int p, msgInfo msg)
{
return msg.priority < p;
}
But the new one should look like this:
bool msgInfo::priority_check(int p)
{
return priority < p;
}
Also, incMsgClass is a bit odd, as it's a non-static class method that returns a msgInfo object. It's difficult to tell without understanding what it's supposed to do, but it seems possible that this function should actually be a constructor, rather than a regular method.
One other thing is that you're currently passing a msgInfo by value to those methods. So if the method needed to modify the passed msgInfo, it would not have any effect. It's generally better to pass objects by reference or const reference to other methods. So, back to the previous non-method example, it should really be this.
bool priority_check(int p, const msgInfo &msg)
...
But, as I said, you probably don't need the msgInfo parameters anyway.
At line 4, is the function incMsgClass being performed on the string message_fr_client
Yes
and returning the resultant (and modified) message_processed?
Whatever it's returning, you're ignoring the return value. It can modify the object itself, yes, because the function is not const.
At line 5, the function priority_check is being performed on the message_processed and returning a boolean?
Yes
In my class definition, I have a function getPath that is meant to modify the value of nodePath - is it just a matter of using message_processed.getPath(/arguments/)?
If a member function is intended to modify one of the class members, it's just a matter of not marking that function const
Hard to tell without implementation-details, but here we go:
I. You are passing a std::string as value (C++ is call-by-value by default), so you get a copy of the std::string in your method. If you want to work on the object you passed and manipulate it, use a reference on the object, like
msgInfo incMsgClass(std::string& original_msg); // notice the ampersand
then you can change your signature to
void incMsgClass(std::string& original_msg);
as you don't need to return the std::string you passed.
II. Yes, at least according to your signature
III. Can see a node_path only as a member.
For all your questions, see C++-FAQ.
Your basic assumptions are correct.
message_processed.incMsgClass(message_fr_client); //line 4
This line is not correct. The function you call returns msgInfo which is simply dropped. You should assign it to something. But it is not as it is usually done. You should make it a constructor of msgInfo, like
class msgInfo
{
public:
msgInfo(std::string original_msg);
...
}
Then you could call it like this
msgInfo message_processed(message_fr_client);
That line would create a msgInfo that is already properly initialized.
There is another pattern for creating class instances - static creating function. In your case you could mark incMsgClass static and then call it like
msgInfo message_processed = msgInfo.incMsgClass(message_fr_client);
I seriously doubt you need this pattern here, so I'd advise to move to constructor.
As of other functions, I see no problems there. Just note that all member functions not marked as const can modify the object they are called on. So, you don't need to pass this object explicitly. For functions a pointer to the object they are called on is available by name this. Also the functions can access all class variables as if these variables are global for normal (non-member) functions.