What does it mean to declare a variable as a function? - c++

In the example below I do
MyClass a ();
I've been told that a is actually a function that returns a MyClass but neither of the following lines work.
MyClass b = a();
a.a = 1;
So what is a and what can I do with it?
#include "stdafx.h"
#include "iostream"
using namespace std;
class MyClass {
public:
int a;
};
int _tmain(int argc, _TCHAR* argv[])
{
MyClass a ();
// a is a function? what does that mean? what can i do with a?
int exit; cin >> exit;
return 0;
}

I've been told that a is actually a function that returns a MyClass [...]
That is a function declaration. It just declares a function called a and makes the compiler aware of its existence and its signature (in this case, the function takes no arguments and returns an object of type MyClass). This means you may provide the definition of that function later on:
#include "iostream"
using namespace std;
class MyClass {
public:
int a;
};
int _tmain()
{
MyClass a (); // This *declares* a function called "a" that takes no
// arguments and returns an object of type MyClass...
MyClass b = a(); // This is all right, as long as a definition for
// function a() is provided. Otherwise, the linker
// will issue an undefined reference error.
int exit; cin >> exit;
return 0;
}
MyClass a() // ...and here is the definition of that function
{
return MyClass();
}

Related

what is the difference when using (); vs ; when creating an object in c++?

in c++, whats the difference between writing something like
myclass myobject();
//and
myclass myobject;
also i'm new to stack overflow so if i'm doing something wrong just tell me.
When you write:
myclass myobject();
You may think you're creating a new object of type myclass, but you actually declared a function called myobject, that takes no parameters, and has a return-type of myclass.
If you want to see that for sure, check this code:
#include <stdio.h>
#include <iostream>
using namespace std;
class myclass
{ public: int ReturnFive() { return 5; } };
int main(void) {
myclass myObjectA;
myclass myObjectB(); // Does NOT declare an object
cout << myObjectA.ReturnFive() << endl; // Uses ObjectA
cout << myObjectB.ReturnFive() << endl; // Causes a compiler error!
return 0;
}
prog.cpp: In function ‘int main()’:
prog.cpp:18:23: error: request for member ‘ReturnFive’ in ‘myObjectB’, which is of non-class type ‘myclass()’
cout << myObjectB.ReturnFive() << endl;
^~~~~~~~~~
The difference is same as,
int a; and int a();
I am pretty sure that you understand now. Just for the sake of answer, I am explaining it below.
int a; // -> a is a variable of type int
int a(); // -> a is a function returning int with void paramters

create an unary_function functor for non-static member function

The code should explain my difficulty. Though the code itself is quite meaningless, I'm planning to add containers in MyClass, and use algorithms with member functions.
#include <cstdlib>
#include <algorithm>
#include <functional>
using namespace std;
class MyClass
{
public:
MyClass() { a = 0; }
~MyClass() {}
private:
int a;
bool tiny_test (int);
int Func();
};
bool MyClass::tiny_test (int b)
{
return a == b;
}
int MyClass::Func()
{
// does not compile
(mem_fun(&MyClass::tiny_test))(this);
// commented below is another attempt, also no success
//mem_fun1_t<bool, MyClass, int> tmp_functor = mem_fun(&MyClass::tiny_test);
//tmp_functor(this);
return 0;
}
int main(int argc, char** argv)
{
return 0;
}
Thanks a lot! Btw, I'm not using a static member function, simply because I believe it must work for non-static member functions.
P.S. Eric, Jarod42, thanks for prompt replies!
bool MyClass::tiny_test (int b)
{ // ^^^^^ You missed this argument
return a == b;
}
Try this:
// Supply one more argument. E.g., 3
(mem_fun(&MyClass::tiny_test))(this, 3);

How do you call a class and its method when its stored in a pointer array

How do you use a pointer and call the class methods it points to?
For example:
Image *img[26];
Image IM = outputImage();
img[0] = &IM;
I want to call img[0], or IM's methods. I tried something like this but I received errors.
img[0].getPixel(0,1);
The error is "expression must have a class type"
Since you are using a pointer array, you must dereference it as a pointer.
img[0]->getPixel(0, 1);
And this:
Image IM = outputImage();
should be:
Image &IM = outputImage();
Assuming that outputImage() returns a reference.
you can use following two methods:
1) use -> operator to the member function.
#include<iostream>
using namespace std;
class myclass
{
public:
void printHello()
{
cout<<"hello from class"<<endl;
}
};
int main()
{
myclass *s[10];
myclass inst;
s[0]=&inst;
s[0]->printHello();
return 0;
}
2) use . after de-referencing the pointer.
#include<iostream>
using namespace std;
class myclass
{
public:
void printHello()
{
cout<<"hello from class"<<endl;
}
};
int main()
{
myclass *s[10];
myclass inst;
s[0]=&inst;
(*s[0]).printHello();
return 0;
}

Function "was not declared in this scope"

I'm new to C++ and get a beginner's mistake:
myclass.cpp: In function ‘int main()’:
myclass.cpp: 14:16: error: ‘func’ was not declared in this scope
This is the code:
#include <iostream>
using namespace std;
class MyClass{
public:
int func(int);
};
int MyClass::func(int a){
return a*2;
}
int main(){
cout << func(3);
}
I hope you can help me.
int main(){
cout << func(3);
}
func is not a global function; it is a member function of the class. You need an instance of the class to access it.
For example:
int main()
{
MyClass obj;
std::cout<< obj.func(3);
}
func is a member function, so it must be invoked through an object. For example:
int main()
{
MyClass obj;
std::cout << obj.func(3); // 6
}
In your example, you treated it as a free function, so the compiler looked for a function with that name. Since it could not find it, it issued a compiler error.
func is a member function of MyClass. To call it, you need an object of MyClass type to invoke it on:
int main(){
MyClass m; // Create a MyClass object
cout << m.func(3);
}
Alternatively, you could make func a static member function, which means that it is not associated with any particular instance of the class. However, you would still need to qualify its name as belonging to the MyClass class:
class MyClass{
public:
static int func(int);
};
int MyClass::func(int a){
return a*2;
}
int main(){
cout << MyClass::func(3);
}

C++ : unresolved overloaded function when using function pointers

#include <iostream>
using namespace std;
class B
{
public:
int getMsg(int i)
{
return i + 1;
}
};
class A
{
B b;
public:
void run()
{
taunt(b.getMsg);
}
void taunt(int (*msg)(int))
{
cout << (*msg)(1) << endl;
}
};
int main()
{
A a;
a.run();
}
The above code has a class B inside a class A, and class A has a method taunt that takes a function as an argument. class B's getMsg is passed into taunt...The above code generated the following error message: "error: no matching function for call to 'A::taunt()'"
What's causing the error message in the above code? Am I missing something?
Update:
#include <iostream>
using namespace std;
class B
{
public:
int getMsg(int i)
{
return i + 1;
}
};
class A
{
B b;
public:
void run()
{
taunt(b.getMsg);
}
void taunt(int (B::*msg)(int))
{
cout << (*msg)(1) << endl;
}
};
int main()
{
A a;
a.run();
}
t.cpp: In member function 'void A::run()':
Line 19: error: no matching function for call to 'A::taunt()'
compilation terminated due to -Wfatal-errors.
I'm still getting the same error after changing (*msg)(int) to (B::*msg)(int)
b.getMsg is not the correct way to form a pointer to member, you need &B::getMsg.
(*msg)(1) is not the correct way to call a function through a pointer to member you need to specify an object to call the function on, e.g. (using a temporary) (B().*msg)(1).
The right way to do such things in OOP is to use interfaces so all you need to do is to define an interface and implement it in B class after that pass the pointer of instance which implements this interface to your method in class A.
class IB{
public:
virtual void doSomething()=0;
};
class B: public IB{
public:
virtual void doSomething(){...}
};
class A{
public:
void doSomethingWithB(IB* b){b->doSomething();}
};
This works in VS 2010. The output is the same on all lines:
#include <iostream>
#include <memory>
#include <functional>
using namespace std;
using namespace std::placeholders;
class A
{
public:
int foo(int a, float b)
{
return int(a*b);
}
};
int main(int argc, char* argv[])
{
A temp;
int x = 5;
float y = 3.5;
auto a = std::mem_fn(&A::foo);
cout << a(&temp, x, y) << endl;
auto b = std::bind(a, &temp, x, y);
cout << b() << endl;
auto c = std::bind(std::mem_fn(&A::foo), &temp, _1, y);
cout << c(5) << endl;
}
Basically, you use std::mem_fn to get your callable object for the member function, and then std::bind if you want to bind additional parameters, including the object pointer itself. I'm pretty sure there's a way to use std::ref to encapsulate a reference to the object too if you'd prefer that. I also included the _1 forwarding marker just for another way to specify some parameters in the bind, but not others. You could even specify everything BUT the class instance if you wanted the same parameters to everything but have it work on different objects. Up to you.
If you'd rather use boost::bind it recognizes member functions and you can just put it all on one line a bit to be a bit shorter: auto e = boost::bind(&A::foo, &temp, x, y) but obviously it's not much more to use completely std C++11 calls either.