Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Is there a way to allocate a variable within the scope of a parameter list? By using new we can do the following :
Class A{ /*... snip ...*/ };
void myFunc(A* a){ }
int main(...){
myFunc(new A());
return 0;
}
This will create a new A. What if the signature of myFunc was
void myFunc(A a);
instead. Is there a syntax to create local instance inside the myFunc() parameter list? I'm looking for something like
myFunc(A());
or
myFunc(A a());
Another use would be for something like :
A a(123);
if(a == A(123)){ }
The net effect is to save one line, but it also creates a scope within the parameters list which makes me wonder if it is allowed at all.
If you just want to create a variable to pass to the function you can use a aggregate initialization / list initialization
#include <iostream>
#include <cmath>
using namespace std;
class A{ /*... snip ...*/ };
void myFunc(A a){ }
int main(){
myFunc(A{});
return 0;
}
Live Example
You can also use this with classes that have constructors that take multiple parameters
#include <iostream>
#include <cmath>
using namespace std;
class A
{
private:
int foo;
int bar;
double foobar;
public:
A(int a, int b, double c) : foo(a), bar(b), foobar(c) {}
};
void myFunc(A a){ }
int main(){
myFunc(A{1,2,3.0});
return 0;
}
Live Example
C++ supports this with the myFunc(A()); syntax you posed in your question.
#include <stdio.h>
char lazybuff[500];
class Point
{
public:
Point (double x, double y) : m_x(x), m_y(y) { }
char * ToString (void) { sprintf (lazybuff, "%f, %f", m_x, m_y); return lazybuff; }
private:
double m_x, m_y;
};
void print_point (Point print_me)
{
printf ("%s\n", print_me.ToString());
}
int main (void)
{
print_point (Point(5, 3));
return 0;
}
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am learning inheritance in C++ and trying to return value from a function "age". All I get back is 0. I have spent hours to figure out, but no luck. This is my code below. I'll greatly appreciate any help on this!
.h class
#include <stdio.h>
#include <string>
using namespace std;
class Mother
{
public:
Mother();
Mother(double h);
void setH(double h);
double getH();
//--message handler
void print();
void sayName();
double age(double a);
private:
double ag;
};
.cpp
#include <iostream>
#include <string>
#include "Mother.hpp"
#include "Daughter.hpp"
using namespace std;
Mother::Mother(){}
Mother::Mother(double h)
{
ag=h;
}
void setH(double h){}
double getH();
void Mother::print(){
cout<<"I am " <<ag <<endl;
}
void Mother::sayName(){
cout<<"I am Sandy" <<endl;
}
double Mother::age(double a)
{
return a;
}
main
#include <iostream>
#include "Mother.hpp"
#include "Daughter.hpp"
using namespace std;
int main(int argc, const char * argv[]) {
Mother mom;
mom.sayName();
mom.age(40);
mom.print();
//Daughter d;
//d.sayName();
return 0;
Your mom.print() does this:
cout<<"I am " <<ag <<endl;
So the problem here is: ag = 0
Your mom.age(40) does this:
return a;
See, it doesn't save your mom's age to your mom variable, it only return what you pass ( here is 40 ), so how could it print ?
Therefore, there are many ways to solve this, if you want to return your mom's age, do cout << mom.age(40) in main()
Or, just:
void Mother::age(double a)
{
ag = a;
}
function age doesn't assign value a to the member ag but instead it returns the value a which it takes as parameter it's such a bad thing.
to get what I want to say in main write:
cout << mom.age(40) << endl; // 40
to make it correct change you function age to:
double Mother::age(double a)
{
ag = a;
return a; // it's redundant to do so. change this function to return void as long as we don't need the return value
}
*** another thing you should do:
make "getters" const to prevent changing member data and only let "setters" not constant. eg in your code: class mother:
double getH()const; // instead of double getH() const prevents changing member data "ag"
You have to use correctly setter and getter. Use the setter to change the age like this :
void setAge(const double &_age) {
ag = _age;
}
If you want to retrieve the value use the getter.
double getAge() const {
return ag;
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I get an input variable in main function. and I want to use this variable in the external function2 that it already is called as a external function again by function1(like the code below). but this variable is undefined at function2. please help me. thanks for all answers. this is an overview of my code:
int main ()
{
int boogh;
cin >> boogh;
function1 (x,y);
}
function1(int x,int y)
{.
.
function2(w,z);
.
.
}
function2(int w, int z)
{
if (boogh>5)
{.
do some thing
.
.
}
}
the function1 and function2 are recursive
The variable is scoped within main, so you can't access it there. You need to get it (or a copy of it) into the scope of function2. One way is to pass it as a function parameter - to both functions, since it has to go through function1 to reach function2:
void function1(int x, int y, int boogh) {
//...
function2(w, z, boogh);
//...
}
void function2(int w, int z, int boogh) {
if (boogh > 5) { // the value is available here
//...
}
}
int main() {
int boogh;
cin >> boogh;
function1(x,y,boogh);
}
Or you could encapsulate the variable and the function(s) that use it in a class:
struct thingy {
int boogh;
void function1(int x,int y) {
//...
function2(w, z);
//...
}
void function2(int w,int z) {
if (boogh > 5) { // class member accessible here
//...
}
}
};
int main() {
thingy t;
cin >> t.boogh;
t.function1(x,y);
}
Or you could use a global variable, but that's nearly always a bad idea.
You must pass the required variable to the functions either by value or by reference:
Passing by value for your case:
// Example program
#include <iostream>
#include <string>
using namespace std;
void function1(int x);
void function2(int x);
int main ()
{
int boogh;
cin>>boogh;
function1 (boogh);
}
void function1(int x)
{
function2(x);
}
void function2(int y)
{
int boogh=y;
if (boogh>5)
{
//do something here
}
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am working on my own GUI framework using C++ and OpenGL. My experience in both is small as this is my first project using them.
In the framework I have created a window, which renders the design of the window, and then any objects that have been added to the window as a child.
I then create the window using a new class called MainMenu that inherits from my window class, I then add a new button to the MainMenu
Using:
button->SetOnClick(&MainMenu::button_Click, this);
I then add a pointer to the function, as well as the instance of the class to the buttons 'SetOnClick' method - Therefore if that button is clicked a method within the MainMenu will run.
This works great at the moment, however my issue now is that I want to add a new window called Settings, which will also inherit from the Window class
Therefore I need to make the function pointer in my button class work for any number of classes (all of type Window)
Here is the code that is currently working - but for only the MainMenu (Please note that I have stripped out a lot of methods that do not relate to the question to make it easier to read)
Window.h:
class Window
{
private:
void Initialize(WindowManager* manager, int width, int height);
public:
Window(WindowManager* manager);
Window(WindowManager* manager, int width, int height);
~Window(void);
void Render();
bool MouseMove(int x, int y);
bool MouseLBDown(int x, int y);
Children* Child() { return m_children; };
MainMenu.h:
class MainMenu : public ObjWindow
{
private:
void Initialize();
public:
MainMenu(WindowManager* manager, int width, int height) : Window(manager, width, height)
{
Initialize();
};
MainMenu(WindowManager* manager) : Window(manager)
{
Initialize();
};
~MainMenu(void);
void button_Click();
MainMenu.cpp:
void MainMenu::Initialize()
{
Button* button = new Button(Vector2D(100, -400), 100, 50);
Child()->Add(button);
button->SetText("Click Me!");
button->SetOnClick(&MainMenu::button_Click, this);
}
void MainMenu::button_Click()
{
//Do some button code
}
Button.h:
class Button
{
typedef void (MainMenu::*Function)();
Function m_onClickFunction;
MainMenu* m_window;
public:
Button(Vector2D position, int width, int height);
~Button(void);
void SetText(std::string);
std::string GetText();
void Render();
bool MouseMove(int x, int y);
bool MouseLBDown(int x, int y);
void SetOnClick(Function, MainMenu*);
Button.cpp:
Button::Button(Vector2D position, int width, int height)
{
m_onClickFunction = NULL;
}
Button::~Button(void)
{
}
bool Button::MouseMove(int x, int y)
{
return true;
}
bool Button::MouseLBDown(int x, int y)
{
if (m_body->Intercepts(x,y))
{
if (m_onClickFunction != NULL)
{
(m_window->*m_onClickFunction)();
}
}
return true;
}
void Button::SetOnClick(Function function, MainMenu* window)
{
m_onClickFunction = function;
m_window = window;
}
From researching around the internet it seems that I need to use a template so that I can handle the class as a type, I have tried fitting this in to my code, but so far I nothing has worked.
Please note that I am also new to asking question on stackoverflow, so if I am missing anything important please let me know
You need to either create a template of the Button class - in your case it would look like this:
template <typename myType>
class Button{
typedef void (myType::*Function)();
Function m_onClickFunction;
myType* m_window;
public:
...
void SetOnClick(Function, myType*);
}
And use it like this:
Button<MainMenu> button;
button->SetOnClick(&MainMenu::button_Click, this);
...or create a delegate class. There are plenty of examples about delegates in C++, if you search for them.
But I'm not so sure if you wan't to stick with passing pointers to functions. You might be better off always calling the same method of derived classes, and using the virtual keyword.
Like this:
class Window{
public:
virtual void button_Click(){};
};
class someDerivedWindow: public Window{
public:
void button_Click(){};
};
and inside the button class just calling:
m_window->button_Click();
You could work and implement your own library to do member function pointers, depending on what the goal of your project is. It is fairly complicated though, and requires a rather deep understanding of C++.
However, you can also use boost::function combined with std::bind or boost:bind, to achieve what you want to do.
If you have
struct X {
int foo(int);
};
You can use:
boost::function1<int, int> f;
X x;
f = std::bind1st(
std::mem_fun(&X::foo), &x);
f(5); // Call x.foo(5)
This example is taken directly from the boost::function documentation - http://www.boost.org/doc/libs/1_55_0/doc/html/function.html
If using C++11:
#include <iostream>
#include <functional>
#include <vector>
#include <cstdlib>
#include <algorithm>
#include <ctime>
using namespace std;
int foo1()
{
return 0;
}
int foo2()
{
return 1;
}
int main()
{
function<int()> f1 = foo1;
function<int()> f2 = foo2;
//do some magic
srand(time(0));
function<function<int()>()> generator = [&]()
{
if(rand() % 2 == 0)
return foo1;
else
return foo2;
};
vector<function<int()>> vec(100);
generate(vec.begin(),vec.end(),generator);
for(auto elem: vec)
cout << elem() << endl;
return 0;
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
Header:
#include <unordered_map>
#include "O.h"
#include "P.h"
using namespace std;
class O{
public:
O();
unordered_map<int,P>* X();
unordered_map<int,P>* Y();
private:
unordered_map<int,P>* b;
unordered_map<int,P>* a;
};
source:
#include "O.h"
#include "P.h"
#include <unordered_map>
using namespace std;
O::O(){
a= new unordered_map<int,P>();
b= new unordered_map<int,P>();
}
unordered_map<int,P>* O::X(){
return b;
}
unordered_map<int,P>* O::Y(){
return a;
}
Error is:
1>O.cpp(76): error : return value type does not match the function
type 1> return b;
1>O.cpp(80): error : return value type does not match the function
type 1> return a;
I'm going crazy trying to debug this....
EDIT: Intel Compiler v13
The code you have posted is valid C++, so the issue must lie elsewhere in your code. I would check the included headers. Here is an example with a valid declaration of P:
#include <unordered_map>
using namespace std;
class P{
public:
int a = 3;
};
class O{
public:
O();
unordered_map<int,P>* X();
unordered_map<int,P>* Y();
private:
unordered_map<int,P>* b;
unordered_map<int,P>* a;
};
O::O(){
a= new unordered_map<int,P>();
b= new unordered_map<int,P>();
}
unordered_map<int,P>* O::X(){
return b;
}
unordered_map<int,P>* O::Y(){
return a;
}
int main(){
O o;
auto map = o.X();
return 0;
}
ideone: http://ideone.com/Y4ydzj
This question already has answers here:
What are access specifiers? Should I inherit with private, protected or public?
(2 answers)
Closed 9 years ago.
How do you guys find the value of s.x from this code
I am beginner of c++ and dont know how to solve it
Please help thanks
// StarterLab.c : C Program to convert to C++
//
//#include "stdafx.h" // required for Visual Studio
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
//#include "MemTracker.h"
#pragma warning (disable:4996)
using namespace std;
struct variable
{
friend void showCalculation(variable a);
private:
int x;
int y;
int sum;
public:
void Calculate(int x,int y);
};
void showCalculation(variable a)
{
printf("%d",a.sum);
};
void variable:: Calculate (int x,int y)
{
sum = x + y;
};
int main ()
{
variable s;
s.Calculate(7, 6);
showCalculation(s);
printf("%d",s.x);
}
How do you guys find the value of s.x from this code
I am beginner of c++ and dont know how to solve it
Please help thanks
The variable x is private, so you cannot access it directly. You could add a member function to get it:
int variable::GetX() {
return x;
}
printf("%d", s.GetX());
You can not access s.x because x is a private member. You have two options.
Create a getter:
int variable::X() { return x; }
or make it public:
public:
int x;
int y;
int sum;
Note that using getters/setters is the appropriate way of doing this.