Changing int value from a class function - c++

I have a shape class that I initialize from my main program and give the parameters in the constructor.
Shape *cusomShape = new CustomShape(float radius, float origin)
The shape class has some functions such as rollover and more.
When the rollover function inside the shape class is fired, I want to change a certain int value in the main program. This might similar to firing of an event that changes the value when the rollover function is fired, but I am not sure how to do that in C++. If at all, events is the ideal approach here, it would great to see a short example coming.
If using the event is not the correct, what would the ideal way to go about this?

I think what you need is to pass a value by pointer or reference to the function in Shape and then modify it. If the function is called not from main but from somewhere else passing the pointer is the better option you have. First pass the pointer to the class and store it using another method and then each time rollover is called make use of it.
EDIT: example:
class CustomShape {
void storePointer(int* _value) {
value = _value;
}
void rollover() {
.. do stuff
*value++; // for instance
... do stuff
}
int * value;
}
int main() {
int a;
CustomShape cs;
cs.storePointer(&a);
....
cs.rollover();
....
return 0;
}

Pass a reference to the variable in the constructor and save that reference. Change the value when needed.

I would suggest passing a reference to the variable to the member function that needs to change its value. Storing a reference in a class couples the Shape class to the reference. This means that each time you want to use the Shape, without updating the integer, you cannot, since the Shape constructor will expect a reference/pointer to the int as an argument (the Shape class will store the pointer/reference as an attribute). Passing a reference/pointer to the member function promotes Low Coupling.
#include <iostream>
class Shape
{
double shapeValue_;
public:
Shape (double value)
:
shapeValue_(value)
{}
void fireFunction(int& updateMe)
{
updateMe = 123;
}
};
using namespace std;
int main()
{
int update;
cout << update << endl;
Shape s(4.5);
s.fireFunction(update);
cout << update << endl;
return 0;
};
And in this case, you have an option for a main program that doesn't involve shape object calling on fireFunction:
int main()
{
Shape s(4.5);
// Main program that doesn't use fireFunction.
return 0;
};
In this case, if you have member functions changing input arguments, you should take on a style for defining such functions: e.g. make sure that the variable that gets changed by the member function is always the first input argument in its declaration.
If you want complex objects to communicate updates between each other, you can make use of the Observer Pattern.

Related

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.

Function pointer delclaration in c++

I have written a class Seat in cpp & I declared a function pointer it it.
class implimentation is given below
Seat.cpp
#include "StdAfx.h"
#include "Seat.h"
int Seat::count = FL;
Seat::Seat(void)
{
seatId = Seat::count;
seatStatus = unoccupied;
Seat::count++;
}
Seat::~Seat(void)
{
}
void Seat::*checkSeatStatus(void)
{
}
Seat.h
#include <string>
using namespace std;
class Seat :
public Vehicle
{
int seatId;
int seatStatus;
static int count;
public:
Seat(void);
~Seat(void);
void (*checkSeatStatus)();
};
it showing error at function pointer declaration :
'checkSeatStatus' : illegal use of type 'void'
What is the reason behind ? , does it need any initialization of function pointer ?
If checkSeatStatus is intended to be a member function it should be:
void* Seat::checkSeatStatus(void) {
...
}
with function prototype within the class declaration of:
void* checkSeatStatus(void);
If it's intended to be a member variable holding a function pointer that you can set then, umm, don't do that... It's very probably the wrong design.
If (per the name) it's just supposed to return the current value of status then it should be a function that returns an int instead of a void *:
int Seat::checkStatus(void) {
return status;
}
NB: I removed Seat from the method name since it should be implicit from the fact that you called it on a Seat object.
This doesn't answer the question you ask, but will show how to use the function in a thread.
Using std::thread it's actually very easy to start a thread using any member function. The important part is that it should be a normal member function, so declared like
class Seat
{
...
public:
...
void checkSeatStatus();
};
Then to create a thread using the function you first need an instance of the class:
Seat seat;
And then you simply create the thread
std::thread my_thread{&Seat::checkSeatStatus, seat};
Do whatever other processing you want to do in the main thread, and then join the thread you had created:
my_thread.join();
There are a couple of important things to know here: The instance of the Seat class (the variable seat above) must live longer than the thread. If it goes out of scope and is destructed before the end of the thread that will lead to undefined behavior.
You must also join the tread before the thread-object (the variable my_thread above) is destructed.

Passing Vector to function while using Graph

I wrote my code like this inside a class to calculate max distance from source to node. Now I need to take it out of the class and have a similar function to calculate my distances but by using Djikstra. So, I would need to pass this city vector and source being one of my vertex ( this will loop over vertices ) and return a distance from this function back to class for my next computation. I am running out of time so help me.
int distanceToNearCity(int cityIdOfStore, const std::vector<City> & AllCities) const
{
// is there a store in this city ?
if (storeExists || cityId == cityIdOfProposedNewStore)
{
return 0; // 0 distance
}
int distance = TOOFAR; // initialise with more than max allowed
for (int i=0; i<connectingCities.size(); ++i)
{
int id = connectingCities[i];
if (AllCities[id-1].hasStore() || AllCities[id-1].getId() == cityIdOfProposedNewStore)
{
// we have a store (or proposed one) here, but is it's distance more than other stores ?
if (distances[i] < distance)
{
distance = distances[i];
}
}
}
return distance;
}
How can I pass these class objects to function which is public.Thanks!!
Well, accessing internal member variables from main is problably a bad design, breaks encapsulation, is a possible source of problems, thus not a good idea.
Solution 1
Let's say your class is called MyOriginal. Make distanceToNearCity virtual. Create a derived class MyDerived and rewrite distanceToNearCity so that implements Djikstra. In the derived class you can access the original member variables from MyOriginal, as long as they are public or protected. The user (main) does not need to know the implementation details.
Solution 2
Rewrite the original distanceToNearCity method so, that it has no side effects as it ware a static method. This means that it does not need access to any of the member variables. Pass all arguments to the method via parameters. I mentioned 'as it was a static method', since the method will not be the member of the original MyOriginal class. Make MyOriginal a template class, implement distanceToNearCity in an external class and pass this class as a template argument to MyOriginal. As a non member, you can implement any number of distance algorithms and pass them to the original class. This solution has the advantage, that the call to the 'virtual' method is known at the compile time, so it produces faster code.
template<class T> // T will contain distance computation
class MyOriginal
{
public:
void process()
{
.. // your staff
int distance = T::distanceToNearCity(necessary arguments); // call the external implementation
.. // rest of your staff
}
};
class OriginalDistance
{
public:
static int distanceToNearCity(necessary arguments); // your original implementation
};
class DjikstraDistance
{
public:
static int distanceToNearCity(necessary arguments); // another distance computation
};
int main(int argc, char *argv[])
{
MyOriginal<DjikstraDistance> myInstance;
myInstance.process(); // call processing, use DjikstraDistance::distanceToNearCity() inside
}
Solution 3
If you from some reason dislike both previous implementations, you can use a 'c' style solution. Create a type which represents a signature of the distanceToNearCity method.
Write 'distanceToNearCityOriginal' and 'distanceToNearCityDjikstra' functions. Pass a pointer to desired function as a paramter the MyOriginal::process method. C++ developers will dislike you.
typedef int (DistanceAlgo*)(necessary arguments); // pointer to a function which returns int
int distanceToNearCityOriginal(necessary arguments); // first implementation of distance
int distanceToNearCityDjikstra(necessary arguments); // second implementation of distance
class MyOriginal
{
public:
void process(DistanceAlgo algo)
{
.. // your staff
int distance = (*algo)(necessary arguments); // call the external implementation
.. // rest of your staff
}
};
int main(int argc, char *argv[])
{
DistanceAlgo algo = &distanceToNearCityDjikstra; // choose djikstra
MyOriginal myInstance;
myInstance.process(algo); // call processing, use distanceToNearCityDjikstra inside
}

Passing integer by reference to a class in c++

I have a thread-class Buffer (own made class), and many derived classes such as BufferTypeA, BufferTypeB...
Since I have to synchronize them in a certain order, I'm giving any of them an integer which represents the order to run certain task. I also have to know inside each thread Buffer which one is next to run the task, so I'm passing every BufferType a reference to an integer which all of them must share and I didn't want to make it Global.
I got lost at any point and I don't see where.
First I create all the BufferTypes from a class where I also define that shared integer as:
int currentThreadOrder;
And when creating the BufferTypes:
int position = 0;
if (NULL == bufferA) {
bufferA = new BufferTypeA(&currentThreadOrder, ++position,
waitCondition);
}
if (NULL == bufferB) {
bufferB = new BufferPos(&currentThreadOrder, ++position,
waitCondition);
}
if (NULL == bufferC) {
bufferC = new BufferRtk(&currentThreadOrder, ++position,
waitCondition);
}
Then, in BufferTypeA header:
class BufferTypeA: public Buffer {
public:
BufferTypeA(int currentThreadOrder,
int threadConnectionOrder = 0,
QWaitCondition *waitCondition = NULL);
//..
}
And in cpp file:
BufferTypeA::BufferTypeA(int currentThreadOrder, int threadConnectionOrder, QWaitCondition *waitCondition):
Buffer(currentThreadOrder, threadConnectionOrder, waitCondition) { }
Now I'll show Buffer header:
class Buffer: public QThread {
public:
Buffer(int &currentThreadOrder,
int threadConnectionOrder = 0,
QWaitCondition *waitCondition = NULL);
//...
protected:
QWaitCondition *waitCondition;
int threadConnectionOrder;
int &currentThreadOrder; // Shared address
}
And finally the cpp:
Buffer::Buffer(int &currentThreadOrder, int threadConnectionOrder, QWaitCondition *waitCondition) {
this->threadConnectionOrder = threadConnectionOrder;
this->waitCondition = waitCondition;
this->currentThreadOrder = currentThreadOrder;
}
And the error I'm getting is error: uninitialized reference member Buffer::currentThreadOrder.
I'm embarrased to ask, because it's going to be a simple problem with pointers and addresses, but I can't see where the problem is, so please help.
When you create a class with a data-member that is a reference, the reference needs to be assigned a value in the constructor initializer list.
References have to be given a value when they are created, they are not pointers. They have to start with a value and that value cannot be changed (while the contents that is pointed to by that value can be changed).
Essentially you can think of a reference as an alias for an existing variable. You can't give a friend a nickname if you don't have a friend :)
RESPONSE TO COMMENT:
You don't "share a reference" between objects. Each object will have its own reference to the same variable. When you "pass by reference" you are telling the compiler that you want the variable in your function to actually be the variable in your outer scope, rather than creating a new variable by value. This means that you only have one variable at one memory location. The reference is just memory in some other place that forwards you to that same memory location.
Think of this as call forwarding... I can have 15 phone numbers in 15 different countries. I can set them all up to forward calls to my cell in the US. So, people are calling me no matter which number they call.
Each of your classes just has another reference to forward the "phone calls" or variable reads/writes to that same memory location. So, you're not sharing a reference between classes, you're making sure that each class HAS a reference to the same underlying memory location.
Back to the metaphore, each class won't have the same phone, but each class' phone will forward to the same number (variable) none-the-less which lets them all set/get the same value in the end.
RESPONSE II:
Here's a simple example to get your head going, it's pretty easy to apply to your classes. I didn't compile it but it should work minus a typo or two possibly.
class A
{
public:
A(int& shared) : m_shared(shared)
{
//No actions needed, initializer list initializes
//reference above. We'll just increment the variable
//so you can see it's shared in main.
m_shared += 7;
}
void DoSomethingWithIt()
{
//Will always reflect value in main no matter which object
//we are talking about.
std::cout << m_shared << std::endl;
}
private:
//Reference variable, must be initialized in
//initializer list of constructor or you'll get the same
//compiler error again.
int& m_shared;
};
int main()
{
int my_shared_integer = 0;
//Create two A instances that share my_shared_integer.
//Both A's will initialize their internal reference to
//my_shared_integer as they will take it into their
//constructors "by reference" (see & in constructor
//signature) and save it in their initializer list.
A myFirstA(my_shared_integer);
A mySecondA(my_shared_integer);
//Prints 14 as both A's incremented it by 7 in constructors.
std::cout << my_shared_integer << std::endl;
}
you pass a pointer int* as 1st argument to BufferTypeA, which expects and int, while you said in your question you meant to use a int&. To do this, the ctor of BufferTypeA should take a int& and initialise it in an initialisation list (i.e. not within the { } part of the ctor) like
class BufferType {
int &Ref;
public:
BufferTypeA(int& ref) : Ref(ref) { /* ... */ }
};
and in your construction of BufferA you must not pass an address, but the reference, i.e.
int counter;
Buffer = new BufferType(counter);
You want code like this:
Buffer::Buffer(
int &currentThreadOrder0,
const int threadConnectionOrder0,
QWaitCondition *const waitCondition0
) :
threadConnectionOrder(threadConnectionOrder0),
waitCondition(waitCondition0),
currentThreadOrder(currentThreadOrder0)
{}
The reason is related to the reason you cannot write
const double pi;
pi = 3.14;
but can write
const double pi = 3.14;
A reference is typically implemented as a constant pointer, to which one cannot assign an address after one has initialized the pointer. Your version of the code assigns, as in the first pi example. My version of the code initializes, as in the second pi example.

Is it possible to pass a variable out of a class without creating a new object in C++

I have a variable, which is a member of one of my classes, that another is in need of, but I'm not sure how to effectively pass the value between them without using a global variable, which is something I'd like to avoid if at all possible. I know I could create an object, but that would invoke the constructor of the originating class which would execute a number of functions and write the needless results to memory, which would be wasteful of system resources.
Is there an easy way to pass this value between the two functions?
Update: The class that is in need of the variable, called no_of_existing_devices. The purpose of class Initialise is to open up a file and count the number of lines of test it contains, and place that number in the variable int no_of_existing_devices, which is then used by the Device::Device() to create an object for each
class Device
{
public:
void view_attribute_list();
void set_attribute();
Device();
};
Device::Device()
{
for (int count = 0; count < no_of_existing_devices; count ++)
{
// Create an object for each iteration, up to a maximum of no_of_existing_devices
}
}
The class of which this variable is a member
class Initialise
{
public:
int no_of_existing_devices;
bool initialisation;
string existing_device_list[100];
void initialise_existing_devices();
Initialise();
};
Initialise::Initialise()
{
no_of_existing_devices = 0;
}
void Initialise::initialise_existing_devices()
{
string line;
ifstream DeviceList;
DeviceList.open("devices/device_list");
while (true)
{
getline(DeviceList, line, '\n');
if (DeviceList.eof())
{
break;
}
++ no_of_existing_devices;
}
DeviceList.close();
DeviceList.open("devices/device_list");
for (int i = 0; i < no_of_existing_devices; i ++)
{
getline(DeviceList, line, '\n');
existing_device_list[i] = line;
}
Device existing_devices[no_of_existing_devices];
!initialisation; // Existing devices are now initialised
}
Okay, from what I understand:
You don't want to have a global
You don't want to have a static
You don't want to introduce a dependency between Device and Initialise
There is one other option, assuming something owns Device and Initialise, move the no_of_existing_devices up to there, then construct both Device and Initialise with a reference to this variable...
In a similar circumstance I was just passing the pointer to the member --- I had to invoke a member function then, so it was a pointer to the member function, http://www.parashift.com/c++-faq-lite/pointers-to-members.html
It's a bit messy, but it works :-).
If the variable in the originating class can hold a value without an instance of the class I would assume that the variable is static. If not create a public static member of the class. And use it in the target class.
Something like:
// .h file
class A
{
public:
static int a;
}
// .cpp file
int A::a = 123;
// .cpp file of class B
void B::foo()
{
cout << A::a;
}
If it is a class attribute (internal variable), then you can obtain a reference through a get method. Otherwise, you can use the friend keyword on the class you want to access the attribtue from the other For example, if you declare friend class B; on class A, the attributes of the class B will be accessible on the class A.
I suggest you use the first method in order to maintain your code OO pure ;)
Edit: of course, if you access through a reference there are no resources wasted :)
Edit 2: use a static method on Initialise class that returns the no_of_existing_devices and call Initialise::NoOfExistingDevices() on the Device class. If you want to resources use a pointer like this:
public static int* Initialise::NoOfExistingDevices() {
return &no_of_existing_devices;
}
By the way, I advise you to turn the variable private.