global function and class reference - c++

I want to send integer value in class to global function from main. How should I send it as a parameter,I am sending the parameters wrong
Tetris
{
private:
int num;
}
printBoard(Tetris &t);
int main()
{
Tetris tetris;
printBoard(board,tetris);
}
i want to send num , to printboard.

There are several problems with the shown code.
First, you're missing the class keyword when defining the class.
Second, the return type of the function is also missing.
Third, the function has only one parameter but you're passing two arguments.
i want to send num , to printboard
You can add a getter called getNum which you can use from inside your free function as shown below:
vvvvv------------->added this class keyword
class Tetris
{
private:
int num = 0; //don't forget to initialize
public:
//add a getter
int getNum() const
{
return num; //return a copy
}
};
vvvv----------------------->added return type as void
void printBoard(Tetris &t)
{
std::cout << t.getNum(); //use the getter
}
int main()
{
Tetris tetris;
printBoard(tetris);
}
Demo

Related

Passing variable from function A to main and back to another

I have the following example
int main() {
...
}
void parameterList() {
...
}
void myMethodA() {
...
}
void myMethodB() {
...
}
void myMethodC() {
...
}
I have read several StackOverflow posts on this subject and understand to pass a variable from myMethodA() to myMethodB(), I will need to call myMethodB() in myMethodA() with the variables. To illustrate
void parameterList() {
...
int someInteger = 45;
string someName = "John";
int otherInteger = 20;
myMethodB(someName, someIntegers);
myMethodC(otherInteger);
}
void myMethodB(string &someName, int &someInteger) {
...
string another_someName = someName;
int another_someInteger = someInteger;
...
}
void myMethodC(int &otherInteger) {
...
int another_someInteger_two = otherInteger;
...
}
parameterList() is a function where it contains multiple variables for multiple myMethod() functions. On initial program run, parameterList() will have to run first in main to get all the necessary variable. Ideally, the main function will obtain all these variables from parameterList() and pass it to myMethod() in main function. To illustrate
Step 1
main function will run parameterList()
Step 2
parameterList() process and have multiple variables meant for multiple myMethod()
Step 3
main function should have a variable that can "store" these variables in order to pass it to all the myMethod() for further processing
The main function will not run myMethodB() until it is told to do so and when the variables from myMethodA() is inside the main.
Any clarification on this is greatly appreciated. Thanks for taking your time!
You could also use a class to wrap data and also manage the lifetime of the objects.
class Context {
int someInteger;
string someName;
Context(int a, const string& b) :
someInteger(a),
someName(b)
{}
void myMethodA() {
/* do something with someInteger and someName */
}
void myMethodB() {
/* do something with the results from myMethodA */
}
};
int main() {
Context ctx{45, "John"};
ctx.myMethodA();
ctx.myMethodB();
}
Passing variable from function A to main and back to another
To pass a value out of a function, you can return it.
To pass a value into a function, you can use a parameter. Example:
int myMethodA() {
int someInteger = 45;
// ...
return someInteger;
}
int main()
{
int someInteger = myMethodA();
myMethodB(someInteger);
}
I don't think this will work if myMethodA() will need to return more than 1 variable
That's not a problem. While only one object can be returned, that object can be of a class type, and classes can contain more than one sub object. Example:
struct example {
int someInteger;
string someName;
};
example myMethodA();
void myMethodB(const example&);
If it makes sense for the structure of the program, the functions could potentially be made member functions of the class such as demonstrated in KamilCuk's answer.
Can the struct have array?
Yes. Class members can be arrays.
Is 'example myMethodA()', is that in the main function?
That is a declaration of a function that returns instance of example.
How should I return these variables in myMethodA() inside myMethodA() return?
Same way as you return other objects. With the return statement.

How do I pass a function within a namespace as a non-namespace parameter?

I need to call a function when a button is pressed. The following function should take in the function to be called:
void ButtonLayer::LoadButton(void(*func)()) {
// do button loading stuff
// if button is clicked...
func();
}
This would work except for the fact that passing a function within a seperate namespace gives the following error:
argument of type "void(OtherLayer::*)()" is incompatiable with parameter of type "void(*)()"
I don't want to make every function I pass static to avoid this problem, so I need some way of converting a function within a namespace to be of type void(*). I have tried static casting but I'm unsure of the exact syntax as I'm new to C++
It seems that you want to pass a member function.
This example may help you.
class A {
public:
int i;
int fun(int j) {
return i + j;
};
};
void fun(int j, A ob, int (A::* p)(int)) {
std::cout << (ob.*p)(j);
}
void main() {
int (A:: * fp)(int); //declare fp as a function pointer in class A
fp = &A::fun; //init fp
A obj;
obj.i = 1;
fun(123, obj, fp);
}
Based on #Yksisarvinen and #MSalters comments, the solution was:
void ButtonLayer::LoadButton(std::function<void()>) {
// do button loading stuff
// if button is clicked...
func();
}
and then to call it:
LoadButton([this] { functionToCall; });

How do I access member variables from one class into other using friend functions in C++?

I am using fried functions for the very time and was assigned to complete an incomplete code using friend functions as below.
//CODE GIVEN IN THE QUESTION NOT MEANT TO BE EDITED
#include<iostream>
using namespace std;
class store_keeper;
class item
{
char prod_name[30];
char prod_code[10];
float prod_price;
int stock_In_Hand;
public:
void get();
void print()const;
friend class store_keeper;
};
class store
{
int num_Of_Items;
item items[20];
public:
void get_details();
void print_details() const;
friend class store_keeper;
};
class store_keeper
{
char name[30];
char id[10];
public:
void get();
void print();
void stock_mgmt(store &);
};
//MY CODE
void item::get()
{
cin>>prod_name>>prod_code>>prod_price>>stock_In_Hand;
}
void item::print() const
{
cout<<prod_name<<prod_code<<prod_price<<stock_In_Hand;
}
void store::get_details()
{
cin>>num_Of_Items;
for(int i=0;i<num_Of_Items;i++)
{
items[i].get();
}
}
void store::print_details() const
{
for(int j=0;j<num_Of_Items;j++)
{
items[j].print();
}
}
void store_keeper::stock_mgmt(store &s)
{
for(int k=0;k<s.num_Of_Items;k++)
{
if(items[k].stock_In_Hand<10)
{
s.print_details();
}
}
}
//CODE GIVEN IN THE QUESTION NOT MEANT TO BE EDITED
main()
{
store s;
store_keeper sk;
s.get_details();
sk.stock_mgmt(s);
}
I had to display the details of the item for which the stock in hand is less than 10.I am getting an error that num_Of_Items was not declared in this scope and suggest any edits if any required.Thanks.
There are few problems with your code, and they are all located in this function:
void store_keeper::stock_mgmt(store &s)
^ ~~~~~~ 1
{
for(int k=0;k<s.num_Of_Items;k++)
{ ^^^^^^^^^^^^^^~~~~~~~~~~~~~ 2
if(s.items[k].stock_In_Hand<10)
{ ^^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 3
s.items[k].print();
} ^ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 4
}
}
1 - you need to give name to this parameter as it is needed inside your function
2 - when compiler see store_keeper::num_Of_Items it thinks you want to access a static variable of name num_Of_Items inside store_keeper class, but there is no such variable. What you want here is to use s. to read num_Of_Items from s which is of type store. You have befriended store_keeper with store so this is legal
3 and 4 - items is a field in store class, which is provided to your function as a parameter s, so use s. to access it.
And finally item has a print and not print_details
This will allow your code to compile, but probably more work is needed to make it work as expected.

Is it possible to access a variable in a sketch from a class (Arduino)?

Say I want to get a value of a variable in a sketch from a class I wrote like
sketch
int device;
void setUp() {
device = 1;
}
And I have a class
SomeClass.cpp
void Device::checkTimedEvent() {
someDevice = device; //variable from sketch
}
I know it's possible to access members from another class where I can include the class and use the :: scope operator but not sure how the sketch relates to classes.
thanks
It appears that the usual C/C++ "extern" syntax works in Arduino as if the sketch file were a .cpp file:
Sketch:
int device = 123;
SomeClass.cpp:
extern int device;
void SomeClass::checkTimedEvent() {
someDevice = device; // variable from sketch
// will display "123" (or current value of device)
// if serial output has been set up:
Serial.println("device: " + String(device));
}
You may need to worry about startup and initialization order, depending on the complexity of your project.
class Test
{
public:
int N = 0;
};
Test t;
int someNumber = t.N;
The best way to do this is to pass the value into the function as a parameter. Here's a simple example:
Class:
class Test
{
public:
void doSomething(int v);
private:
int myValue;
};
void Test::doSomething(int v)
{
myValue = v;
}
Sketch:
Test t;
int someNumber;
void setup()
{
someNumber = 27;
t.doSomething(someNumber);
}
The setup() function here passes global variable someNumber into the class's member function. Inside the member function, it stores its own copy of the number.
It's important to note that it has a completely independent copy of the number. If the global variable changes, you'd need to pass it in again.
As much as Bloomfiled's answer is correct using the the more accepted practice of employing Getter and Setter functions. Below demonstrates this along with making the attribute public and directly accessing it.
class Test
{
public:
void SetMyValue(int v);
int GetPublicValue();
int GetPrivateValue();
int myPublicValue;
private:
int myPrivateValue;
};
void Test::SetMyValue(int v)
{
myPublicValue = v;
myPrivateValue = v;
}
int Test::GetPublicValue()
{
return myPublicValue;
}
int Test::GetPrivateValue()
{
return myPrivateValue;
}
Test t;
int someNumber;
void setup()
{
someNumber = 27;
t.SetMyValue(someNumber); // set both private and public via Setter Function
t.myPublicValue = someNumber; // set public attribute directly.
someNumber = t.GetPublicValue(); // read via Getter
someNumber = t.GetPrivateValue();
someNumber = t.myPublicValue; // read attribute directly
}
void loop() {
// put your main code here, to run repeatedly:
}

pointer on method as an argument

To avoid code duplication, I'm tring to pass pointers to functions as arguments of a static method.
I have a class (Geo) with only static methods. One of this methods (+++Geo::traceRay(+++)) should just display(Geo::display(+++)) few things, then return an int.
Another class (Las) needs to use the Geo::traceRay(+++) method, but should display(Las::display(+++)) someting else.
So I try to pass a pointer to function argument to the Geo::traceRay(+++, pointer to function) method. the pointed functon will the right "display()" method.
Up to now, passing the first pointer to display() is not an issue, but I can't find how to do it with the second one.
class Geo
{
public:
static bool display(int pix);
static int traceRay(int start, int end, bool (*func)(int) = &Geo::display); // no issue with this default parameter
};
class Las
{
public:
bool display(int pix);
void run();
};
int Geo::traceRay(int start, int end, bool (*func)(int))
{
for (int i = start; i < end ; ++i )
{
if((*func)(i)) return i;
}
return end;
}
bool Geo::display(int pix)
{
cout << pix*100 << endl;
return false;
}
bool Las::display(int pix)
{
cout << pix << endl;
if (pix == 6) return true;
return false;
}
void Las::run()
{
bool (Las::*myPointerToFunc)(int) = &display; // I can just use display as a non member class, but it should stay a member
Geo::traceRay(0,10, myPointerToFunc); // issue here!
}
int main()
{
Geo::traceRay(0,10); // use the "normal display" = the default one// OK
Las myLas;
myLas.run();
return 0;
}
You can't pass a member function pointer as a function pointer. I presume making Las::display static is not an option. In that case, I would suggest taking a std::function and using std::bind to bind the current instance:
static int traceRay(int start, int end, std::function<bool(int)> func = &Geo::display);
...
Geo::traceRay(0,10, std::bind(&Las::display, this, std::placeholders::_1));
Also, in both cases, you can call func by:
func(i);
No need to dereference it first.
What Chris suggests is great if that's as far as it goes.
Another approach to this, which would be beneficial if you have several shared functions like that, would be to use an interface (with a virtual method Display(+++)) with two implementations, put an instance of the implementation in question in each of Geo and Las (or Las could directly implement the interface). Then traceRay takes a reference to the interface base class and calls the display method on it.