constructors and destructors - c++ - c++

I need to write a program that prints 100 stars on the screen (at random places), and then the stars disappear slowly - one after another. I'm not allowed to use loops nor recursions.
I've tried to play with the constructors and the destructors but I can't get the stars to disappear one after another (and not all together).
Any ideas?
Thanks,
Li
Sorry - forgot to mention i'm using c++
My current access violating useless code:
class star {
int x;
int y;
public:
star(){
x = rand()%80;
y = rand()%80;
PaintcharOnRandomLocation('*',x,y);
};
~star(){
PaintcharOnRandomLocation(' ',x,y);
};
};
class printAll{
star* arr;
public:
printAll(){
arr = new star[100];
};
~printAll(){
delete[] arr;
};
};
void doNothing(printAll L){
};
void main()
{
srand ( time(NULL) );
doNothing(printAll());
getch();
};

Seems the only way possible without loops/recursion is something like this:
class Star
{
Star()
{
//constructor shows star in a a random place
}
~Star()
{
//destructor removes star and sleeps for a random amount of time
}
};
int main()
{
Star S[100];
}
This is really just a dumb trick because the compiler has to run the constructor for each star to initialise the array and then the destructor for EACH star as it goes out of scope.
It is also a bad trick as all the workings that go in the main function are opaque and invisible. It would obviously be better to use a loop in this context and putting the delay inside a destructor like this is really confusing and unmaintainable.

This is not a runtime recursion:
template<int N>
struct Star
{
Star() { DrawAtRandomPlace(); }
~Star() { RemoveSlowly(); }
Star<N-1> star;
};
template<> struct Star<0> {};
int main()
{
Star<100> stars;
}
The code above will generate 100 different instantiations of the Star template. RAII will guarantee the order of drawing and removing.

Based on your final comment, can you have the destructor of your star class do a delay? See for example the sleep or usleep functions.

Since Destructors/Constructors are only an Idea, they're probably not the right title for your question.
I don't know what system/environment you are in, but how about this:
Create a buffer that contains a string with your stars, simply manually by typing them in the code.
Next, write a function that displays the buffer to whatever output window you use.
Then, you would need a function that has a static(!) pointer to the back of the buffer, and that does the following:
Call the buffer printing function
Write a null byte under the current pointer position
Decrement the static pointer
Wait for a period of time
Raise a custom signal with raise()
In the main() function, you set the the Signal Handler for your custom signal to the function described above, and then you raise the custom signal.

Related

C++ Accessing a class from a function it is not defined in

I'm new to C++ and having a bit of trouble with accessing variables inside a class. From what I've read on here so far creating globals is a really bad practice and not to do that, but I dont know how else to move access to a class around.
So far my searches have pointed me to set and get functions in the class, but I think I can only use them in the block where the object is defined.
Basically what I want to know is if I define a class object in main() then call a function in main like gameLoop() how do I access that object inside that new function without making the class object global.
For instance:
#include "stdafx.h"
#include <iostream>
using namespace std;
#include <string>
class Word
{
private:
string m_word;
int m_length;
public:
void set(string word, int length)
{
m_word = word;
m_length = length;
}
};
void gameLoop()
{
word1.set(); //flags error as it cant acces the word1 object
//I want to be able to access word1 from here
//Not a copy because that wouldnt change the actual word1
//I dont want to define it in here because then it would be created again
//for each loop of gameLoop
}
int main()
{
Word word1;
int play = 1;
while (play ==1){
gameLoop();
}
return 0;
}
This is a largely simplified version but for the purpose of the game I want the class to be stored externally but for a number of gameplay functions inside gameLoop to be able to access and change the class object.
Ideally, the dependencies of a function should be stater in the parameter list. If your gameLoop function requires a Word object, pass it in as an argument. That way, it's clear what objects the function requires to work. This would look something like:
void gameLoop(Word& word)
{
word.set();
// ^ Obviously you need to supply args here.
}
int main()
{
Word word1;
int play = 1;
while (play ==1){
gameLoop(word1);
}
return 0;
}
And since you're mutating the Word object in the function, you need to pass it by reference, or else you're just modifying a copy.
Your only other sane option would be to make the word object global, but that should be avoided at all costs. It makes testing more difficult since you need to take into consideration every change that may have happened, which makes it difficult to isolate problems.
If you're structuring you're program this way, you would have to pass it as a parameter to gameloop
However, This is a very poor design, since anything you create in main and want to access in gameloop would have to be passed in as an argument. I would consider a different approach.
You could move the entire loop and variable declarations into gameLoop as so:
void gameLoop()
{
Word word1;
int play = 1;
while (play ==1){
word1.set(/*args*/);
}
}
int main()
{
gameLoop();
return 0;
}
This way you won't have to pass a million things into gameloop. Generally in games there's some initialization and finalization that needs to take place as well, and this can all be done in main before/after the call to gameLoop.
So to answer you original question, you would have to pass word1 as an argument to gameLoop(). So redefine your function to accept a Word argument, and then pass in word1. but again, I would reconsider your current design before its too late

Instantiate only one class at a time, out of a group of classes, to save memory

The following is directly related to this. What I would like is to be able to call and have active only one class at a time, to save memory, but also because I plan to add, later on, a GUI, so I'd be able to call the classes through a drop-down menu (for example).
I tried making composition, and this is what came out:
#include <iostream>
class Power
{
private:
double m_x;
public:
Power() {std::cout<<"Power\n";}
Power(double x): m_x {x} {std::cout<<"Power("<<x<<")\n";}
~Power() {std::cout<<"~Power\n";}
const double getX() const { return m_x; }
};
class Scanner
{
private:
Power m_power;
public:
Scanner() {std::cout<<"Scanner\n";}
Scanner(const Power &p): m_power {p} {std::cout<<"Scanner("<<&p<<")\n";}
void print() {std::cout<<"x="<<m_power.getX()<<'\n';}
};
class Printer
{
private:
Power m_power;
public:
Printer() {std::cout<<"Printer\n";}
Printer(const Power &p): m_power {p} {std::cout<<"Printer("<<&p<<")\n";}
void print() {std::cout<<"x="<<m_power.getX()<<'\n';}
};
class Copier // if Copier is to be used for "unification", will "public" be needed?
{
private:
Scanner *m_s;
Printer *m_p;
int m_i;
public:
Copier() {std::cout<<"Copier\n";}
Copier(const Power &p, int i): m_i {i}
{
if (i)
m_s = new Scanner(p);
else
m_p = new Printer(p);
std::cout<<"Copier("<<&p<<","<<i<<")\n";
}
void print() { std::cout << (m_i ? m_s->getX() : m_p->getX()) << '\n'; }
};
int main(int argc, char *argv[])
{
Scanner *s {new Scanner(Power(2.3))};
s->print();
Printer *p {new Printer(Power(3.14))};
p->print();
s->print(); // here, both *s and *p exist, both use memory
// this comes after considering adding class Copier
Copier *c {new Copier(Power(1.618), 0)};
c->print();
c = new Copier(Power(2.718), 1);
c->print();
return 0;
}
Ignore Copier for a bit. As it is, I can use it, and this is what comes out:
Power(2.3)
Scanner(0x7ffc80d98c10)
~Power
x=2.3
Power(3.14)
Printer(0x7ffc80d98c20)
~Power
x=3.14
x=2.3
The (major) problem now is that there are multiple objects in memory, there's *s and there's *p, as you can see x can pe printed out with both 3.14 and 2.3. If I have more than 2 classes (which I do), I could call each class and each will take up memory. That's not something I want.
How can I call only one class at a time and not have to call extra resets or deletes? I thought of adding another class for it, see Copier. But I can't use std::unique_ptr and the solution in the code is, not only extremely ugly, but doesn't even work. Plus it calls constructors like crazy.
I tried using std::unique_ptr in a simple function, with std::make_unique (that needs c++14, and I'd rather keep some larger safety margin, but I could also live with it, too). It also doesn't work because it points to Power (if I call z->print() it says 'class Power' has no member 'print'):
std::unique_ptr<Power> call(const Power &p, const int &i)
{
if (i)
return std::make_unique<Printer>(p);
else
return std::make_unique<Scanner>(p);
}
I don't know how to make this. In short, classes Scanner, Printer, and any other that exist, are dedicated classes that perfom one task, only, unique in their way of computing, and all of them make use of some common variables in Power (besides their own). I don't think it would be very effective to move the common variables to each class because they would only bloat the code, and, as I understand it, "if you can use a storage class instead of repeating the same variable over and over, use it" (not my words, is this true?). Then, I'd like to be able to instantiate those classes, but only have one active at a time, to spare memory.
As an example, suppose one class makes an array of 1mil values, then another makes 1mil different values, and so on. Imagine having that array in memory as many times as there are instantiated classes. I don't want that. The purpose of Copier would have been to call (based on the conditional) only one class at a time. Job done? Call another, but forget anything else that was done before, start anew. And all this to be able to call through only one widget, such as select from list, click&go, that will be added later.
That was a stupid mistake, I forgot to delete public ... after copy-pasting. I also tried the code now (with Copier), it compiles, but still doesn't work, m_x stays empty, even with the very ugly solution of having two Scanner and Printer pointers as member variables inside Copier.
Well, after some tries, I couldn't make what I wanted so I thought to go back to my original idea, even if it meant inheritance. So I came up with this piece of code, where I changed the names to make a bit more sense(?):
#include <iostream>
class Garage
{
protected:
double m_x; // gas, tires, etc, that all cars use, reside in the Garage
public:
Garage() {std::cout<<"Garage\n";}
virtual ~Garage() {std::cout<<"~Garage\n";}
};
class Audi: virtual public Garage
{
public:
Audi() {std::cout<<"Audi\n";}
void f(const double &x) { m_x=x; std::cout<<"Audi::f("<<x<<")\n";}
};
class Bmw: virtual public Garage
{
public:
Bmw() {std::cout<<"Bmw\n";}
void f(const double &x) { m_x=x; std::cout<<"Bmw::f("<<x<<")\n";}
};
class Driver: public Audi, public Bmw
{
private:
double m_y; // report of driving, based on m_x
public:
Driver() {std::cout<<"Driver\n";}
Driver(const double &x, int i)
{
if (i)
Bmw::f(x);
else
Audi::f(x);
m_y = -m_x;
std::cout<<"Driver("<<x<<","<<i<<")\n";
}
void print() { std::cout << "x=" << m_x << ", y=" << m_y << '\n'; }
};
int main(int argc, char *argv[])
{
Driver *d {new Driver(1.618, 0)};
d->print();
d = new Driver(0.618, 1);
d->print();
// even iteration works now
delete d;
d = nullptr; // to be sure it's dead(?)
for (int i=0; i<2; ++i)
{
d = new Driver(3.14, i);
d->print();
}
return 0;
}
Now, this works, but I have a feeling I set a new record on bad code example. Please don't bash me for this, rather point out all the mistakes, or how you would do it to achieve the same result. Still, even if it seems to work as I want, it still calls all the constructors, on all branches, instead of only on the needed ones. I realize (my apologies) I forgot to say that Driver, here, is also responsible for using m_x further, for its m_y (that's why the code is a bit different).
I'd like to point out that I am not fixed in keeping this code, or any other, I am willing to change and adapt, as long as I reach my purpose. But since I am a beginner, I can't make too many combinations, so I am left with presenting whichever result it is that I reached to try and make myself understood. The program above, as it is, when run, gives what I want, even has the possibility of making a loop, which will let me use it much easier in a GUI, later on. The names, as they are, make the most sense in composition, Garage has-a Bmw, and that was what I tried, but I couldn't obtain what I wanted. So, even if this uses inheritance and does not make sense that an Audi is-a Garage, I kept the names to suggest my initial tryout with composition. My main reason for posting this is to show what I would like the program to do. What happens in main() will be used in a GUI, I am thinking of Qt, because I'd like this to run on all 3 major OSes. So having the possibility of calling one car at a time, using it, and also being able to store previous information without having stale objects in memory, only m_x*nr_of_cars, will make it much easier to work with.
Here is one way to do it.
{ // scope begins
Printer p; // note, no pointers
p.print();
} // scope ends, p is gone
Here we have an object that appears, does one thing once, and disappears.
Here is another
boost::variant<Printer,Scaner,Copier> psc(Printer());
psc.get<Printer>().print();
psc = Scaner(); // the printer is gone
Use some std::unique_ptr constructor:
std::unique_ptr<Power>
call(const Power &p, const int &i) {
if (i)
return std::unique_ptr<Power>(new Printer(p));
else
return std::unique_ptr<Power>(new Scanner(p));
}
Perhaps what you really want is a tagged union. Follow the rule of five. See this for inspiration.

Get call identifier or address of a function

Suppose that I have this code:
class MyClass
{
public:
void SomeFunction()
{
// Find somehow if this is first, second, or third call of a function in a main loop
// If the function is called first time create new variables that will be used just for this function call
}
};
MyClass myClassObject;
int main()
{
myClassObject.SomeFunction(); // First call
myClassObject.SomeFunction(); // Second call
myClassObject.SomeFunction(); // Third call
}
How can I know inside function what number of call is it?
Note that I will probably have 100 function calls placed in code. Also this should work in Visual Studio on Windows and Clang on Mac.
I had one workaround:
void SomeFunction(const char* indetifier = "address")
{
CheckAddress(indetifier); // This will check if address is stored. If it is not, create variables, if it is, if addresses matches use variables that are tied to that address.
}
I tried not to assign a new string to an "indetifier" and to let it to use default string ("address"). This of course didn't worked well as compiler will optimize "indetifier", so I was thinking that maybe a solution would be to disable optimizations for that variable, but I didn't because there should be some more elegant solution.
Also one thing came on my mind, maybe I could force inline a function and then get it's address, but this also seams like bad workaround.
I could also create new classes for every call but I would like to avoid this as there will be a lot of function calls and I don't want to think 100 different names.
If there is a way to create class object only at first call this would be awesome.
I hope that you understand what I want, sorry if something is not that clear as I am beginner coder.. :D
EDIT:
I can't use static for variables in a class because software that I am developing is a plugin that could have multiple instances loaded inside host and this will probably mess up the variables. I have tested static variables and if I create for example "static int value" anywhere and write something in it in one instance of a plugin this "value" will be updated for all instances of a plugin and this is not something that I want.
void SomeFunction()
{
// Find somehow if this is first, second, or third call of a function in a main loop
// If the function is called first time create new variables that will be used just for this function call
}
If the first call is to be tracked per object, then you need a member variable that keeps track of how many times SomeFuntion has been called for that object.
If the first call is to be tracked independent of objects, then you can use a static function variable that keeps track of how many times SomeFuntion has been called for that object.
I can't use static for variables in a class because software that I am developing is a plugin that could have multiple instances loaded inside host and this will probably mess up the variables. I have tested static variables and if I create for example "static int value" anywhere and write something in it in one instance of a plugin this "value" will be updated for all instances of a plugin and this is not something that I want.
So make a non-static counter?
class MyClass {
int count;
public:
MyClass () : count(0) { }
void SomeFunction () {
++ count;
// do stuff with 'count'
}
};
MyClass myClassObject;
int main () {
myClassObject.SomeFunction(); // First call
myClassObject.SomeFunction(); // Second call
myClassObject.SomeFunction(); // Third call
}
Or just pass it as a parameter...
class MyClass {
public:
void SomeFunction (int count) {
// do stuff with 'count'
}
};
MyClass myClassObject;
int main () {
myClassObject.SomeFunction(1); // First call
myClassObject.SomeFunction(2); // Second call
myClassObject.SomeFunction(3); // Third call
}
But I'm really wondering what you're actually trying to do, and I highly suggest sitting back and rethinking this whole thing, because there are a number of red flags / confusing points here...
If you're only interested in checking whether it's the first call, you can add a bool SomeFunction_first_call; to the MyClass, to act as a flag. The constructor sets the bool to true. MyClass::SomeFunction() uses the conditional check if (SomeFunction_first_call) /* ... */ to determine whether it's the first call, as follows:
class MyClass
{
bool SomeFunction_first_call;
public:
MyClass() : SomeFunction_first_call(true) {}
void SomeFunction()
{
if (SomeFunction_first_call)
{
// This code only executes on first call.
do_something();
// Successfully handled first call, set flag to false.
SomeFunction_first_call = false;
}
// This code always executes.
do_something();
}
};
Similarly, if you're only concerned about the first HOWEVER_MANY_CALLS calls, where HOWEVER_MANY_CALLS is a number, you can use something like this:
#include <cstdint>
class MyClass
{
uint8_t SomeFunction_calls;
public:
MyClass() : SomeFunction_calls(0) {}
void SomeFunction()
{
// This segment will be executed until (SomeFunction_calls == HOWEVER_MANY_CALLS).
// After this, the segment will be skipped, and the counter will no longer increment.
if (SomeFunction_calls < HOWEVER_MANY_CALLS)
{
// This code only executes on first HOWEVER_MANY_CALLS calls.
do_something();
// Increment counter.
++SomeFunction_calls;
}
// This code always executes.
do_something();
}
};
Make sure to use the appropriately signed variable for the number of calls that need special handling (i.e. uint8_t for 0..255, uint16_t for 256..65,535, etc.). If different instances of MyClass will need to keep track of a different number of calls, then use a non-type template parameter to indicate this, and optionally, a defaulted typename to indicate what type the counter should be.
#include <cstdint>
template<uint64_t N, typename T = uint64_t>
class MyClass {
T SomeFunction_calls;
...
void SomeFunction()
{
if (SomeFunction_calls < N) {
...
}
...
}
};
In this case, a MyClass<4> will have special treatment for the first 4 calls to SomeFunction(), a MyClass<4444444444444444444> will have special treatment for the first 4,444,444,444,444,444,444 calls, and so on. The counter will default to uint64_t, as that should be large enough to hold the value; when only a smaller number of calls need special treatment, you can specify a smaller type, such as MyClass<4, uint8_t> or MyClass<444444444, uint32_t>.
In C++ you can use the static keyword in a local variable context to create the object only once at the first call:
#include <iostream>
struct MyObject {
MyObject() {
std::cout << "Creating instance " << this << "\n";
};
};
void foo() {
static MyObject my_instance;
std::cout << "... inside function foo ...\n";
}
int main(int argc, const char *argv[]) {
std::cout << "About to call foo...\n";
foo();
std::cout << "... second call ...\n";
foo();
std::cout << "... third call ...\n";
foo();
return 0;
}
With the above code you will notice that only on object MyObject will be created, on the first call to foo.
Note that if your function is a template then for each instantiation of the template you will get another distinct static variable. For example with:
template<int N>
void foo() {
static MyObject my_instance;
std::cout << "... inside function foo ...\n";
}
the all the calls to foo<1>() will use the same variable but calling instead foo<2>() will access another copy of the function (another instantiation of the function template), that will have its own distinct static variable created on the first call to foo<2>(). All static variables that have been initialized will be destroyed after the end of main when the program terminates.

Using list made by classes

Well, I just started learning c++ and i seem to have some problem. To be specific i have to make a program that recreates the game musical chairs. For this i was supposed to make two classes one named member that would have the position of a player and their id number and also point to the next (last member should point to first.). Second a class named chain that would point at the first member and also have the total number of exsting players. For starters i should create the chain based on a parametre N that would give every member a random id and position them and of course link the powers with each other.
What i wrote was
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
class Member{
public:
int position, number;
Member *next_member;
void Member2( Member *member_, int pos, int id,int N){
if(pos <= N){
member_->position=pos;
member_->number=id;
Member2 (member_->next_member, pos++, rand(), N);
if(pos == N)
member_->next_member = this;
}
}
};
class Chain {
Member *First_member;
int size;
public:
Chain ( int N){
size = N;
srand(time(NULL));
First_member->Member2(First_member, 1 , rand(), N);
}
};
and the main just called chain.
The problem is that when Member2 is called by itself, the whole thing crashes. Any help is good.
Edit: When trying to debug it, it seems there is segmentantion fault when membber_ is used after Member2 has called the Member2 isnide it.
The expression pos++ uses post increment, which produces the original value of pos as the expression result. Thus the pos argument does not increase in the recursive call. Thus, you get infinite recursion, which if you're lucky crashes when it's used up all stack space.
There are several issues (at least) with that code:
1)
Member *First_member;
is only a declaration. To turn it into a definition, you need to actually allocate memory, e.g:
Member *First_member = new Member;
and also release it in the end, e.g. (not necessarily the best way to do it, but my C++ is a little rusty):
void free(Member* _member) {
Member* _next = _member->next_member;
if (_next!=NULL) free(_next);
delete _member;
}
Member* First_member = new Member;
// some code ...
free(First_member);
2) More serious problem is your Member2 method: it does not check whether its Member *member_ arguments is not NULL (in which case the code will indeed crash, because it tries to work with garbage as if it was data).
3) Member2 should also take care about allocating memory for the next element in the chain, e.g.:
if (member_->next_member == NULL) {
member->next_member = new Member;
}
Member2 (member_->next_member, pos++, rand(), N);

How to modify a C++ structure with int *

I have the following structure:
struct CountCarrier
{
int *CurrCount;
};
And this is what I want to do:
int main()
{
CountCarrier carrier = CountCarrier();
*(carrier.CurrCount) = 2; // initialize the *(carrier.CurrCount) to 2
IncreaseCount(&carrier); // should increase the *(carrier.CurrCount) to 3
}
void IncreaseCount(CountCarrier *countCarrier)
{
int *currCounts = countCarrier->CurrCount;
(*currCounts)++;
}
So, my intention is specified in the comments.
However, I couldn't get this to work. For starters, the program throws an exception at this line:
*(carrier.CurrCount) = 2;
And I suspect the following line won't work as well. Anything I did wrong?
struct CountCarrier
{
int *CurrCount; //No memory assigned
};
You need to allocate some valid memory to the pointer inside the structure to be able to put data in this.
Unless you do so, What you ar trying to do is attempting to write at some invalid address, which results in an Undefined Behavior, which luckiy in this case shows up as an exception.
Resolution:
struct CountCarrier
{
int *CurrCount; //No memory assigned
CountCarrier():CurrCount(new(int))
{
}
};
Suggestion:
Stay away from dynamic allocations as long as you can.
When you think of using pointers always think whether you really need one. In this case it doesn't really seem that you need one, A simple int member would be just fine.
You need to create the pointer. ie. carrier->CurrCount = new int;
*(carrier.CurrCount)
This is dereferencing the pointer carrier.CurrCount, but you never initialized it. I suspect this is what you want:
carrier.CurrCount = new int(2);
I seriously doubt that your program throws an exception at the line:
*(carrier.CurrCount) = 2;
While throwing an exception is certainly allowed behaviour, it seems much more likely that you encountered an access violation that caused the process to be killed by the operating system.
The problem is that you are using a pointer, but your pointer is not initialised to point at anything. This means that the result of the pointer dereference is undefined.
In this situation there does not seem to be any advantage to using a pointer at all. Your CurrCount member would work just as well if it was just a plain int.
If you are using C++, then you should encash its facilities. Instead of correcting your code, I am showing here that how the code should look like:
struct CountCarrier
{
int CurrCount; // simple data member
CountCarrier(int count) : CurrCount(count) {} // constructor
CountCarrier& operator ++ () // overloaded operator
{
++ CurrCount;
return *this;
}
};
We are overloading operator ++, because you have only one data member. You can replace with some named method also, like void IncrementCount().
CountCarrier carrier(2);
++ carrier;
As Als said, you need to provide some memory for the code to work.
But why make it so complicated? You don't need any pointers for the code you have to work. The "modern C++" way looks more like this:
struct CountCarrier
{
public:
CountCarrier(int currCount) : currCount(currCount) {}
void IncreaseCount() { ++currCount; }
int GetCount() const { return currCount; }
private:
int currCount;
};
int main()
{
CountCarrier carrier(2); // Initialize carrier.currCount to 2
carrier.IncreaseCount(); // Increment carrier.currCount to 3
}
Note how much cleaner and less error prone that is. Like I said, pick up a good introductory C++ book and read through it.