Having trouble dynamically allocating an array with a created class in C++ - c++

I've actually managed to successfully do a dynamically allocated array with a normal data type, but it was a while ago (like, six chapters!) And I can't figure out why I can't set the array dynamically here - I know it's giving me an int error, but I can't use the class type because the class type doesn't deal with numbers like that. At this point I'm pretty confused. Here's my code including headers:
#include <iostream>
#include "milTime.h"
#include "Time.h"
using namespace std;
int main()
{
milTime *theta;
bool amOrPm;
int milHr, milSc,milM,times;
cout<<"How many times would you like to convert?";
cin>>times;
theta = new milTime;
*theta = times;
And here's my error:
Error 1 error C2440: '=' : cannot convert from 'int' to 'milTime
*' c:\users\heather\documents\visual studio 2012\projects\military time\military time\source.cpp 17 1 Military Time
Any help would be greatly appreciated, as I'm completely done except for that. Me and my bright ideas to let it be dynamically allocated!
Here's the milTime class that was requested:
#ifndef MILTIME
#define MILTIME
#include <iostream>
#include "Time.h"
class milTime : public Time
{
protected:
int milHours;
int milMins;
int milSeconds;
public:
void setTime(int h)
{
milHours = h;
}
void setMin(int m)
{
milMins=m;
}
void setSec(int s)
{
milSeconds=s;
}
int getmilHours()
{return milHours;}
int getmilMins()
{return milMins;}
int getmilSeconds()
{return milSeconds;}
bool timeConverter(int mTime, int mMins, int mSecs)
{
bool aOrPm;
min = mMins;
if(mTime<12)
{
hour = mTime;
aOrPm = false;
//AM will be false.
}
else if (mTime>12 && mTime<=24)
{
hour = mTime%12+1;
aOrPm = true;
}
sec = mSecs;
return aOrPm;
}
};
#endif

there are already answers why your code doesn't work
just in case you wanted to allocate an array of milTime, you will need to do it like this:
theta = new milTime[times];
this will create times of milTime objects
anyway, you should be using std::vector instead of dynamic allocations, this is much safer

What is the definition of milTime?
You are trying to assign an int, which is an inbuilt integer type, into your own type milTime. Which won't work unless your type has an assignment operator which takes an int.
Does your type have a constructor that takes an int? as in that case you would want something more like:
theta = new milTime(times);

theta is a pointer to miltime but times is an int hence *theta = times; fails.

Here's your problem:
*theta = times;
theta is a class of milTime, times is an int.
You'll probably need to create a setter method in milTime, like this:
theta.setTime( times )
I can't see your milTime class though, can you post it as well?

Well it seems that in this line:
*theta = times;
You try to assign an int to a milTime.
you can fix this by either doing a static cast:
*theta = static_cast<milTime>(times);
Or oldschool cast:
*theta = (milTime) times;
But prefarbly you can add a constructor to milTime (in miltime.h):
milTime(int i) : someInnerDataWhichIsAnInt(i) {}
The last one is preferable as casts are a sign of a bad structure.
To use the last one do this:
theta = new milTime(times);
Or is it because you need an array? Prefaably use:
std::vector<milTimes> theta() // You need to remove prior definition of `theta`.

Related

Matrix of pointers using subscription

So a few days ago I asked and received a very good answer in this thread. Assignment and retrieval using subscript and equals operator overloads
Unfortunately my mistake but it was a little to far from my end use scenario, I'm trying to store pointers to the cchar_t class in nucrsesw/ncurses.h This is what I have currently
#include <iostream>
#include <vector>
#include <string>
#include <ncursesw/ncurses.h>
#include <ncursesw/panel.h>
class Matrix {
std::vector<std::vector<cchar_t*>> m;
public:
Matrix(int x = 0, int y = 0) {
m.resize(x);
for (int i = 0; i < x; ++i)
m[i].resize(y);
}
class Proxy {
std::vector<cchar_t*> &mm;
public:
Proxy(std::vector<cchar_t*> &c) : mm(c) {}
cchar_t& operator[](int index) {
return *mm[index];
}
};
Proxy operator[](int index) {
return Proxy(m[index]);
}
};
int main() {
wchar_t wR = u'W';
cchar_t *w;
setcchar(w, &wR, 0, COLOR_PAIR(0), NULL);
Matrix m(1, 1);
m[0][0] = *w;
std::cout << typeid(m[1][1]).name() << std::endl;
}
I keep getting invalid initialization of reference type in the second subscript overload function. It may be obvious but CPP is not my primary language. Does anyone know how this can be adapted to store pointers? Thanks in advance.
Note the code is edited to show exactly what happens when it seg faults on me.
mm is a reference to an std::vector which holds objects of type cchar_t* (pointers to cchar_t objects). The subscript operator of std::vector returns a reference to the object at the appropriate index. In your case, that would be a reference to a pointer to cchar_t.
To fix your problem, you can dereference the obtained pointer in the return statement: simply change it to return *mm[index];.

Run-Time Check Failure #2 - Stack around the variable 'e' was corrupted. occurred

#include<iostream>
#include <list>
using namespace std;
class Euler {
private:
int korifes = 0;
int akmes = 0;
int* pinakas[];
public:
void print() { cout << *pinakas[0]; return; }
Euler(int korifess, int akmess);
~Euler() { delete[] *pinakas; }
void addAkmes(int kor1, int kor2);
};
Euler::Euler(int korifess, int akmess) : akmes(akmess), korifes(korifess) {
*pinakas = new int(korifes);
*pinakas[0] = 89;
}
int main() {
Euler e(2, 1);
e.print();
}
Run-Time Check Failure #2 - Stack around the variable 'e' was corrupted. occurred...i can not find where i am wrong in my code.
There are a number of errors in your code, all related to the nature of the pinakas member variable. As it stands, you are declaring this as an array of pointers (to int), and, furthermore, you are using a non-standard syntax for 'flexible' arrays (the empty []).
I don't normally just paste 'fixed' code as an answer but, in this case, that code (with the added \\\ comments where I've made changes) is likely to be the most succinct way to help you.
Although, as many here will no doubt point out, it is far better to avoid the use of 'raw' pointers and the new and delete operators, and use the std::vector container, instead.
#include <iostream>
#include <list>
//using namespace std;/// This is considered 'bad practice' by many programmers
using std::cout;/// Just use the aspect of the STL that you need!
class Euler {
private:
int korifes = 0;
int akmes = 0;
int* pinakas;/// This will point an 'array' of integers
public:
void print() {
cout << pinakas[0]; return;/// No longer any need for the dereference (*)
}
Euler(int korifess, int akmess);
~Euler() {
delete[] pinakas;/// No need for the dereference (*)
}
// void addAkmes(int kor1, int kor2);/// You haven't provided an actual definition for this, but your never use it!
};
Euler::Euler(int korifess, int akmess) : akmes(akmess), korifes(korifess)/// NOTE: Members are initialized in DECLARATION order!
{
pinakas = new int[korifes];/// Use "[]" (not "()") to allocate an array!
pinakas[0] = 89;/// No need for the dereference (*)
}
Feel free to ask for any further clarification and/or explanation.

error when erasing object in vector. how do i add move assignment operators to my classes?

I am getting an error when I am trying to erase an object from my vector
googled but I can't understand what's wrong. from what I gathered I am calling the erase function correctly but I have to provide a move assignment operator to my classes?
my function where i call the erase
void removegroup(const short &group){
switch (tracker[group].group){
case 0: {
guardvec.erase(guardvec.begin()+tracker[group].position); //this is the problem it compiles just fine if i comment out this line
//guardvec.erase(remove(guardvec.begin(), guardvec.end(), tracker[group].position),guardvec.end()); //tried this and it doesnt work
}
break;
}
for (short counter=0;counter<tracker.size();counter++)
if ((tracker[counter].group==tracker[group].group)&&(tracker[counter].position>tracker[group].position))
tracker[counter].position=tracker[counter].position--;
}
my class
class guardhitdice {
friend class guard;
short const times = 2, dice = 8, plus = 2;
};
class guard : private guardhitdice {
private:
short units, XP, morale, totalHP=0, dead=0, wounded=0;
short* HP = new short[units];
public:
void showstats(){
std::cout << "STR=1, DEX=1, CON=1, INT=0, WIS=0, CHA=0, Perception=2, Passive Perception=12"<<std::endl
<<"current xp: "<<XP<<"total HP across units: "<<totalHP<<"casualties: "<<dead<<"wounded: "<<wounded;
}
void initializeHP(){
for (short counter=0; counter<units-1; counter++){
HP[counter]=plus + D(times, dice);
totalHP+=HP[counter];
}
}
guard(const short &xp, short &Units, short &Morale){
XP=xp;
units=Units;
morale=Morale;
// short* HP = new short[units];
initializeHP();
}
~guard(){
delete HP;
}
};
here is my compiler error https://pastebin.com/KSniFkVD
it should be able to remove the object at tracker[group].position. btw position is a short
i also tried adding this to my classes but they don't work
guardhitdice& guardhitdice ::operator=(guardhitdice&&);
guard& guard ::operator=(guard&&);
it works if I do it for normal vectors but not for vectors of objects
Your problem can be reduced down to
#include <vector>
class test{
short const times = 2;
};
int main()
{
std::vector<test> t;
t.push_back(test{});
t.erase(t.begin()); //<-- BAM!
}
Example: https://ideone.com/MlwUyI
vector does a lot of copy-and-assigning. Copying is cool, but test contains a const member. You can't change a const variable, so you can't assign it.
But since it's initialized with a literal and there's no constructor that'll allow the value to be initialized to something else, all instances of test will have the same value. That's a pretty good fit for static. static variables don't take part in assignment, so the default assignment operator is usable.
class test{
static short const times = 2;
};
Example: https://ideone.com/npUi4B

Putting a class constructor overload INSIDE another overload of the same class

Hey so i'm working on a stopwatch class using windows GetTickCount() and the STL, but have run into a problem in that when implementing the Stopwatch(int DecNumb) constructor into the overload Stopwatch(int DecNumb, char command[]) the "accuracy" data type is not set correctly in the latter constructor.
(it seems to return to the former value of the unsigned long int 560345 or something...)
Here's the class and main() commands i'm using to test it:
class Stopwatch
{
protected:
int accuracy;
unsigned long int initial_ilu;
unsigned long int current_ilu;
long float output_fl;
vector<long float> times;
public:
Stopwatch(int DecNumb) { // so accuracy*10 isn't 0
accuracy = 1;
for(;DecNumb>0;DecNumb--) // the Tick count will
accuracy = accuracy*10;}; // diveded by accuracy (each 0 in this number moves the decimal over once)
Stopwatch(int aDecNumb, char command[]) {Stopwatch::Stopwatch(aDecNumb);
if(command = "start") Stopwatch::Start();};
void Start(){initial_ilu = GetTickCount()/*/accuracy*/;};
long float ElapsedTime()
{
current_ilu = GetTickCount()/*/accuracy*/;
output_fl = (current_ilu - initial_ilu)/accuracy;
return output_fl;
};
void Wait(long float seconds)
{
for(unsigned long int waitTime = GetTickCount() + (seconds*accuracy);
waitTime > GetTickCount();) {}
// stay stuck in for loop until time specified is up
};
void SaveTime(){times.push_back(GetTickCount()/*/accuracy*/);};
long float GetTime(int location){if(times.size()<location+1) return times[location+1];
else return -1;};
};
And here's main()
int main()
{
Stopwatch myStopwatch(3,"start");
for(;;)
{
myStopwatch.Wait(2);
cout << myStopwatch.ElapsedTime() << endl;
}
return 0;
}
Why is accuracy not staying at the value i set it too in the constructor? Thanks! =)
oh and any other feedback on my code is welcome! (i'm rather new)
Stopwatch::Stopwatch(aDecNumb);
This does not call the other constructor; it isn't even valid C++.
You can't call one constructor from another constructor for the same object. Only one constructor is called during the creation of an object (not including base class or member constructors, of course).
You don't really need two constructors here, though; one will suffice:
Stopwatch(int DecNumb, char* command = 0) {
accuracy = 1;
for(; DecNumb > 0; DecNumb--) {
accuracy = accuracy * 10;
}
if (command && std::string(command) == "start") {
Start();
}
}
If you really do need two constructors, your best bet is either to use a base class that performs initialization that is common to multiple constructors or to use an "initialize" member function that can be called from the multiple constructors.
Stopwatch(int aDecNumb, char command[]) {Stopwatch::Stopwatch(aDecNumb);
if(command = "start") Stopwatch::Start();};
//Stopwatch::Stopwatch(aDecNumb); is used to declare a constructor outside the class definition, here this utilisation is wrong, it does't make anything.
You could build a class and use it as interface/ or as a Base Class add derive from it if you really want to initialise the constructors.

Problem passing a list of objects to another class, C++

Below I have written a sample program that I have written to learn about passing a list of objects to another class. I talk about the problems I am having below.
#include <iostream>
#include <vector>
using namespace std;
class Integer_Class
{
int var;
public:
Integer_Class(const int& varin) : var(varin) {}
int get_var() { return var; }
};
class Contains_List
{
typedef Integer_Class* Integer_Class_Star;
Integer_Class_Star list;
public:
Contains_List(const Integer_Class_Star& listin) : list(listin) {}
Integer_Class* get_list() { return list; }
};
int main (int argc, char * const argv[])
{
// Create a vector to contain a list of integers.
vector<Integer_Class> list;
for(int i = 0; i < 10; i++)
{
Integer_Class temp_int(i);
list.push_back(temp_int);
}
This is where the errors start occuring. Could someone please look at the second class definition and the code below and shed some light on what I'm doing wrong. Thank you so much, as always!
// Import this list as an object into another object.
Contains_List final(list);
// Output the elements of the list by accessing it through the secondary object.
for(int i = 0; i < 10; i++)
{
cout << final.get_list()[i].get_var();
}
return 0;
}
You don't mention what sort of errors you are getting, but one very obvious problem with your code is that the constructor for Contains_List expects a pointer to Integer_Class while the parameter you are sending it (list) is of type vector<Integer_Class>.
A vector is not the same as an array, so you cannot pass it as pointer to the type it contains. Either change your constructor to accept a vector or pointer/reference to vector, or change the code that is causing you problems so that it sends it a pointer to an array.
The 'Contains_List' constructor takes in an 'Integer_Class*'
You declare 'list' to be of type 'vector', yet you pass it to the the 'Contians_List' constructor. You should change the 'Contains_List' class so that it holds a vector instead of an Integer_List array. The two are not interchangeable.
You could also change the vector to be an array of Integer_List's instead, if you so wished.