Function pointer in c++ class [duplicate] - c++

This question already has answers here:
get function member address
(2 answers)
Closed 8 years ago.
I am trying to use function pointer in a c++ class but got an error.
#include <cstdio>
#include <iostream>
using namespace std;
class abc{
public:
void hello(){
printf("Hello world\n");
}
abc(){
void (*hw)(void);
hw = &hello;
hw();
}
}
int main()
{
abc ab;
return 0;
}
Error
error: cannot convert ‘void (abc::*)()’ to ‘void (*)()’ in assignment
But the following code works for me which is in code base. Can anyone please help me to find out the difference?
void hello(){
printf("Hello world\n");
}
int main()
{
void (*hw)(void);
hw = &hello;
hw();
return 0;
}

Function pointers are (unfortunately) completely different from method pointers, as the error is trying to indicate. This is because the object that the method works on needs to be passed in somehow, which is what makes methods fundamentally different from functions in the first place (and obviously affects how the call is done through the pointer). Method pointers are not even always the same size (and can be significantly larger than a function pointer) when multiple/virtual inheritance comes into play.
You need to declare a method pointer, and call it on behalf of an object of the right type using one of the esoteric .* or ->* operators:
class abc {
public:
void hello(){
printf("Hello world\n");
}
abc() {
void (abc::*hw)();
hw = &abc::hello;
(this->*hw)(); // or (*this.*hw)()
}
}

Related

error: cannot declare pointer to ‘void’ member [duplicate]

This question already has answers here:
Explanation of function pointers
(4 answers)
Closed 8 months ago.
I have the following scenario: I have a third party library and a header associated with it, that I'm using in my project. I completed my project and now I'm unit testing my code and I want to use a stub library, created by myself, for the third party library.
The header for the third party library contains structures that looks like this:
typedef struct{
int (*init)(int * var);
void (*close)(void);
} AInterface
To create my stub version, I created a .cpp file, in which I include the header, and started to implement it like this:
int AInterface::*init(int* var)
{
return 0;
}
void AInterface::*close(void)
{}
But when I compile my code I get the following error: "stub.cpp:76:33: error: cannot declare pointer to ‘void’ member
void AInterface::*close(void)"
I have searched the internet but with no success.
My questions are:
what I am doing wrong here?
is there another way to implement the stub?
I have also tried to implement the stub like this:
int initAInterface(int * var);
int (AInterface::*init)(int * var) = &initAInterface;
int initAInterface(int* var)
{
return 0;
}
But I get the following error:
error: cannot convert ‘int (*)(int*)’ to ‘int (AInterface::*)(int*)’ in initialization
int (AInterface::*init)(int* var) = &initAInterface;
Also I have no main in my stub .cpp file.
Those are function pointers and expect you to give static functions to them, then pass the struct to the library
//#################################################################
//Library header
typedef struct {
int (*init)(int* var);
void (*close)(void);
} AInterface;
//#################################################################
//A CPP file somewhere
//You might need extern "C" if you're mixing C and C++
#include "LibraryHeader.h"
int myInitFuction(int* var)
{
std::cout << "I wrote the init function for this" << std::endl;
return 0;
}
void myCloseFunction(void){
std::cout << "I wrote the close function for this" << std::endl;
}
//Or some other function doesn't need to be main if it's not the entry point
int main()
{
AInterface myInterface;
myInterface.init = myInitFuction;
myInterface.close = myCloseFunction;
SomeLibraryFuction(&myInterface);
}

Passing an array of objects to Member Function in c++

I use Turbo C++ and am experiencing an unexpected error in my code, please help..
I am trying to pass an array of objects to a member function.
An error : Undefined structure test , pops on the line where i define my print function
#include<iostream.h>
#include<conio.h>
class test
{
int t;
public:
void print(test T[])
{
cout<<"This Test\n";
}
};
void main()
{
clrscr();
test T1,T2[5];
T1.print(T2);
getch();
}
I have to use the outdated version of the Turbo C++ compiler at school so the syntax of the code might be different than the new compilers.
Define your function as void print(test *T).
Turbo C++ is broken in the regard of parameters of type test[] being equivalent to test*.

Threads in Constructor in C++ [duplicate]

This question already has answers here:
Start thread with member function
(5 answers)
Closed 6 years ago.
I'm trying to create threads in a constructor of a class that will run a couple of functions inside that class, I've tried this:
ServerLogic::ServerLogic(SOCKET sock)
{
this->sock = sock;
this->dispatchThread = new std::thread(this->dispatchMessage);
}
void ServerLogic::dispatchMessage(){
/*
* this function will handle the connetions with the clients
*/
char recievedMsg[1024];
int connectResult;
//receive data
while (true){
connectResult = recv(this->sock, recievedMsg, sizeof(recievedMsg), 0);
//in case everything good send to diagnose
if (connectResult != SOCKET_ERROR){
this->messagesToDiagnose.push(std::string(recievedMsg));
}
else{
/*
* destructor
*/
}
}
}
but it's giving me an errors:
'ServerLogic::dispatchMessage': function call missing argument list; use '&ServerLogic::dispatchMessage' to create a pointer to member.
IntelliSense: function "std::thread::thread(const std::thread &)" (declared at line 70 of "C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\thread") cannot be referenced -- it is a deleted function.
I think that the error message is basically telling you what to do. Consider the following code (which is problematic, but just serves to illustrate the point):
#include <thread>
class foo
{
public:
foo()
{
std::thread(&foo::bar, this);
}
void bar()
{
}
};
int main()
{
foo f;
}
To specify a member function, use
std::thread(&foo::bar, this);

Request for member 'print' in 'y', which is of non-class type [duplicate]

This question already has answers here:
Why is there no call to the constructor? [duplicate]
(3 answers)
Closed 9 years ago.
I am going through Nicola Josuttis's OOP in C++ book and experimenting with his code using Code Blocks IDE. I am having difficulty understanding the compiler error message. I created a simple class interface (frac1.hpp), a class (frac1.cpp), and a test with main() - (ftest.cpp). The class accepts two integers which is printed out as a fraction. The class constructors set a default of 0 if called w/o any arguments, an integer value if called with 1 argument, or a fraction if called with 2 arguments. If one or two arguments are passed there is no compile error. But if no arguments are passed I expected the constructor to be initialized to 0, instead I get a compiler error about the print statement being of "non-class type". It is as though the object wasn't created. Any help or explanation of what I am doing wrong is greatly appreciated.
thank you kindly for your consideration.
Class description:
//frac1.cpp
#include "frac1.hpp"
#include <iostream>
#include <cstdlib>
//default constructor
Fraction::Fraction() : numer(0), denom(1) //initialize fraction to 0
{
//no further statements
}
Fraction::Fraction(int n) : numer(n), denom(1) //whole integer initialization
{
//no further statements
}
Fraction::Fraction(int n, int d) : numer(n), denom(d)
{
if (d==0) {
std::cerr << "error: denominator is 0" <<std::endl;
std::exit(EXIT_FAILURE);
}
}
void Fraction::print()
{
std::cout<<numer<<'/'<<denom<<std::endl;
}
Interface Description:
//frac1.hpp
#ifndef FRAC1_HPP_INCLUDED
#define FRAC1_HPP_INCLUDED
#include <istream>
#include <cstdlib>
namespace CPPDemo {
// Fraction Class
class Fraction {
private:
int numer, denom;
public:
Fraction();
Fraction(int);
Fraction(int,int);
void print();
};
}
#endif // FRAC1_HPP_INCLUDED
test file description:
//ftest.cpp
#include "frac1.hpp"
#include <iostream>
#include <cstdlib>
int main()
{
CPPDemo::Fraction y();
y.print(); //flagged as compiler error**
}
Message from Compiler:
C:\Users\User\Desktop\CPPDemo\FractionClassTest\ftest.cpp:9: error: request for member 'print' in 'y', which is of non-class type 'CPPDemo::Fraction()'
Change the test file to:
int main()
{
CPPDemo::Fraction y;
y.print(); //flagged as compiler error**
}
Without the () the compiler does not see y.prints as a function call. My knowledge of C++ syntax rules is not good enough to give a better explanation. sorry.
change
CPPDemo::Fraction y();
**y.print;
to
CPPDemo::Fraction y;
y.print();
Because the first declares a function, it does not declare the object you wanted.
And the print function needs brackets (I don't know what the ** were for)
You forgot the function braces ().
Try
y.print()
Oh damn, that got me again. You also need to fix the instanciation
CPPDemo::Fraction y;

Object creation Anomaly [duplicate]

This question already has answers here:
Why is there no call to the constructor? [duplicate]
(3 answers)
Closed 8 years ago.
I am using Code::Blocks 10.05 with GCC on Windows 7. I was experimenting with C++ constructors and I compiled and executed the following program.
#include<iostream>
using namespace std;
class base {
public:
base() {
cout<<"\n Constructor Invoked\n";
}
};
int main() {
base ob;
return 0;
}
The output was as expected and shown below.
Constructor Invoked
But while typing the program I accidentally compiled the following program. To my surprise it compiled without any error or warning.
#include<iostream>
using namespace std;
class base {
public:
base() {
cout<<"\n Constructor Invoked\n";
}
};
int main() {
base ob();
return 0;
}
But the program didn't give any output, just a blank screen. But no error or warning. Since it hasn't called the constructor I assume no object was created. But why no error or warning? Am I missing something very obvious?
When I added the line cout<<sizeof(ob); I got the following error message.
error: ISO C++ forbids applying 'sizeof' to an expression of function type
So what is ob? Is it considered as a function or an object?
Please somebody explain the line of code base ob(); and what actually happens in the memory when that line of code is executed?
Thank you.
You have declared a function with
base ob();
It will do nothing.
See here