How to use weak function in C++ - c++

I am trying to use weak function in a class in C++. Below is what I wrote:
#include <stdio.h>
#include <iostream>
class A {
public:
void func(int argc, char *argv[]) __attribute__((weak));
};
// optional definition:
#if 0
void A::func(int argc, char *argv[]) {
printf("In func()\n");
for(int aa = 0; aa < argc; aa++){
printf("arg %d = %s \n", aa, argv[aa]);
}
}
#endif
int main(int argc, char *argv[]) {
A a1;
if (a1.func){
a1.func(argc, argv);
} else {
printf("func() not available\n");
}
return 0;
}
But this gives below compilation error:
main.cpp: In function ‘int main(int, char**)’:
main.cpp:21:16: error: cannot convert ‘A::func’ from type ‘void (A::)(int, char**)’ to type ‘bool’
if (a1.func){
^
If I move the func() outside a class and use gcc instead of g++, it compiles fine and works as expected. Can someone please tell what's the problem. Basically I want to achieve calling some class functions only if they are available (an optional feature) without using Compiler flags in cpp file.

C++ has a standard mechanism for this. No need for linker tricks.
class Base {
public:
virtual void func(int argc, char *argv[])
{
printf("func() not available\n");
}
};
class A : public Base {
public:
#if 0
void func(int argc, char *argv[]) override;
#endif
};
#if 0
void A::func(int argc, char *argv[]) {
printf("In func()\n");
for(int aa = 0; aa < argc; aa++){
printf("arg %d = %s \n", aa, argv[aa]);
}
}
#endif
int main(int argc, char *argv[]) {
A a1;
a1.func(argc, argv);
}

Related

c++ read access violation after casting

I have a static method inside my class, which I use for a callback.
Inside this callback I want to add a value to result.
This seems not to be possible because of the recast(?).
Is there a way to access the member variable result and add values to it after recasting, or do I need to think of a different way?
MyClass.h
class MyClass
{
public:
vector<string> result;
static int c_CB(void *data, int argc, char **argv, char **azColName);
int Callback(int argc, char **argv, char **azColName);
void Do(string query);
}
MyClass.cpp
void MyClass:Do(string query)
{
sqlite3_exec(this->dbResource, query.c_str(), this->c_CB , NULL, &this->errorMsg);
}
int MyClass::c_CB(void *NotUsed, int argc, char **argv, char **azColName)
{
MyClass* bar = reinterpret_cast<MyClass*>(NotUsed);
// after reinterpret cast, it does not work
//bar->result.insert(bar->result.end(), "foo");
// function call works
return bar->Callback(argc, argv, azColName);
}
int MyClass::Callback(int argc, char **argv, char **azColName)
{
cout << "working" << endl;
}
main.cpp
int main()
{
MyClass* cl = new MyClass();
cl->Do("something");
}
The documentation states that the fourth argument to sqlite3_exec is passed as the first argument of the callback.
Currently you are passing NULL, which you then cast to a MyClass* and attempt access the object, which results in undefined behaviour.
Use this as the fourth argument in place of NULL.
It seems you are trying to access a non-static member function from a static member callback function c_CB.
You were able to call a member function Callback but nothing from the class is accessible, but if I'm correct, the compiler just interpreted Callback as a static function.
If you actually breakpoint inside this function, you can see that none of your member variables actually have a memory address. And the current class, this is null
I'm not sure if the cout << statement still works or if its causing the problem
This is a possible solution to your issue, although it may not be the best one.
class MyClass
{
public:
vector<string> result;
static int c_CB(void *data, int argc, char **argv, char **azColName);
int Callback(int argc, char **argv, char **azColName);
void Do(string query);
void MemberFunction()
{
cout << "working" << endl;
}
static MyClass* currentClass; //Add a static class pointer and assign your class address to it before firing the callback.
}
MyClass* MyClass::currentClass = NULL;
void MyClass:Do(string query)
{
sqlite3_exec(this->dbResource, query.c_str(), this->c_CB , NULL, &this->errorMsg);
}
int MyClass::c_CB(void *NotUsed, int argc, char **argv, char **azColName)
{
MyClass* bar = reinterpret_cast<MyClass*>(NotUsed);
// after reinterpret cast, it does not work
//bar->result.insert(bar->result.end(), "foo");
// function call works
return bar->Callback(argc, argv, azColName);
}
int MyClass::Callback(int argc, char **argv, char **azColName)
{
currentClass->MemberFunction();
}
int main()
{
MyClass* cl = new MyClass();
MyClass::currentClass = this;
cl->Do("something");
}

Int main inside a class

Simple question, how can I run a program having main inside a class?
I have a code:
MojSwiat2.cpp:
int Main::main() {
// code
return 0;
}
And MojSwiat2.h:
class Main {
public:
int main();
};
Main run;
int Main::main() { // with this I have error: function int Main::main(void) already has a body
run.main();
} // and without I got unresolved external symbol _main referenced in function __tmainCRTStartup
Reason I need to do this: Accessing protected members of class from main
By defining a normal main that only contains a call to your other function. Like this:
int main(int, char**) {
return Main().main();
}
int main(int argc, char* argv[])
{
Main m;
return m.main();
}
or if Main::main is declared static
int main(int argc, char* argv[])
{
return Main::main();
}
You still need to define main.
class my_app {
int main(int argc, char* argv[])
{
// ...
}
}
my_app app;
int main(int argc, char *argv[])
{
return app.main(argc, argv);
}

C++ Identifier Not Found error

I get identifer not found error for "startProcess":
int main(int argc, char* argv[])
{
bool result=startProcess(argc, argv);
return 0;
}
bool startProcess(int argc, char* argv[])
{
}
But why?
Functions need to be at least declared before you use them, if not defined. Try putting this at the top of your file.
bool startProcess(int argc, char* argv[]);
The above is a declaration, you're telling the compiler that at some point, you're going to provide a definition for the function, which is this:
bool startProcess(int argc, char* argv[])
{
code here...
}
This difference between a declaration and a definition is important for being able to separate your code into separate files. If you had placed your definition of startProcess in a different file, the compiler would never actually see it while compiling the file that contains main. However, with the declaration, you're making a promise that it exists somewhere.
You haven't declared that function before main(), so the compiler is unaware of the existence of startProcess at the point of call:
bool startProcess(int argc, char* argv[]); // <== Informs the compiler about
// the existence of startProcess
// (and about its signature)
int main(int argc, char* argv[])
{
bool result = startProcess(argc, argv); // OK because of the declaration
// above: the compiler knows that
// somewhere (possibly in another
// translation unit) the definition
// of startProcess is provided
return 0;
}
bool startProcess(int argc, char* argv[])
{
// ...
}
Alternatively, you can put the definition directly before main():
bool startProcess(int argc, char* argv[])
{
// ...
}
int main(int argc, char* argv[])
{
bool result = startProcess(argc, argv);
return 0;
}
You should put the declaration of startProcess before main if you would like to put definition of it after main.
bool startProcess(int argc, char* argv[]); //declare here
int main(int argc, char* argv[])
{
bool result=startProcess(argc, argv);
return 0;
}
bool startProcess(int argc, char* argv[])
{
}
or you can put the definition of startProcess directly before main.
Make a prototype before your main function.
bool startProcess(int argc, char* argv[]);

main.cpp:22:34: error: ‘xxxxxxx’ was not declared in this > scope

I came across this error:
main.cpp:22:34: error: ‘getTotalSystemMemory’ was not declared in this
scope
#include <unistd.h>
#include <cstdlib>
#include <stdio.h>
#include <iostream>
using namespace std;
/*
*
*/
int main(int argc, char** argv) {
cout << "Hello World! \n";
cout << getTotalSystemMemory();
return 0;
}
long getTotalSystemMemory()
{
long pages = sysconf(_SC_PHYS_PAGES);
long page_size = sysconf(_SC_PAGE_SIZE);
return pages * page_size;
}
I assumed the the method ‘getTotalSystemMemory’ is in scope since it is within the same class
You need to provide at least a declaration before you use the function:
long getTotalSystemMemory(); //declaration
int main(int argc, char** argv) {
//...
cout << getTotalSystemMemory();
//...
}
long getTotalSystemMemory()
{
//...
}
You have to declare the function first with C/C++.
Put this before main
long getTotalSystemMemory();
You must "prototype" the function if you are going to be defining it below int main() {}:
long getTotalSystemMemory();
int main() {
/* ....... */
getTotalSystemMemory();
}
long getTotalSystemMemory() {}
in c++ you must write the function before the functions that use it.
if you don't want to write the function in the top, you must put a prototype before.
prototypes look like that:
<return-value> <function name> (<parameters type>);

wxWIDGETS IN C++ Errors In The Program-Edited

I have the following code and i am programming in c++ :-
I followed the instructions given here by the members and changed the code as :-
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <wx/thread.h>
#include <wx/log.h>
#include <wx/app.h>
using namespace std;
class MyThread;
class MyThread : public wxThread {
public:
MyThread(unsigned int& c);
virtual ~MyThread();
wxThreadError Create(unsigned int stackSize = 0);
wxThreadError Run();
wxThreadError Delete(ExitCode* rc = NULL, wxThreadWait waitMode =
wxTHREAD_WAIT_BLOCK);
virtual ExitCode Entry();
private:
unsigned int& counter;
};
MyThread::MyThread(unsigned int& c)
{
counter = c;
}
MyThread::~MyThread()
{
}
wxThread::ExitCode MyThread::Entry()
{
while(counter < 0xFFFFFFFF)
++counter;
return 0;
}
int main(int argc, char** argv) {
unsigned int uiCounter = 0;
MyThread *mt = new MyThread(unsigned int&);
if (mt) {
if (mt->MyThread::Create() == wxTHREAD_NO_ERROR) {
if (mt->MyThread::Run() == wxTHREAD_NO_ERROR) {
}
}
mt->Delete();
}
char cChar = ' ';
while (cChar != 'q') {
cout << uiCounter<< endl;
cChar = (char) getchar();
}
return 0;
}
And have faced the dollowing errors now
newmain.cpp: In constructor 'MyThread::MyThread(unsigned int&)':
newmain.cpp:38:1: error: uninitialized reference member 'MyThread::counter' [-
fpermissive]
newmain.cpp: In function 'int main(int, char**)':
newmain.cpp:57:33: error: expected primary-expression before 'unsigned'
In this problem what i am doing is that i have got two threads one is the main() and other one i have derived from wxthread
The compiler messages tell you how to remove the errors. Start at the top and tackle them one by one.
newmain.cpp:23:25: error: 'Entry' declared as a 'virtual' field
so the error is in this line
virtual void *Entry(LPVOID param);
Take a look at the definition of wxThread::Entry() which can be found here http://docs.wxwidgets.org/2.8/wx_wxthread.html#wxthreadentry
You will see immediately that the base method has a return value and no parameters. The function you create to override the base method must do the same.