Error calling function of a class - c++

I just started writing some code for a class what will be an engine for an analysis, it's simple right now since I'm getting to grips with the stuff I can do with the libraries I import (the bpp ones):
#include <string>
#include <iostream> //to be able to output stuff in the terminal.
#include <Bpp/Seq/Alphabet.all> /* this includes all alphabets in one shot */
#include <Bpp/Seq/Container.all> /* this includes all containers */
#include <Bpp/Seq/Io.all> /* this includes all sequence readers and writers */
class myEngine
{
public:
myEngine();
~myEngine();
void LoadSeq();
};
void myEngine::LoadSeq()
{
bpp::Fasta fasReader;
bpp::AlignedSequenceContainer *sequences = fasReader.readAlignment("tester.fasta", &bpp::AlphabetTools::DNA_ALPHABET);
std::cout << "This container has " << sequences->getNumberOfSequences() << " sequences." << std::endl;
std::cout << "Is that an alignment? " << (bpp::SequenceContainerTools::sequencesHaveTheSameLength(*sequences) ? "yes" : "no") << std::endl;
}
int main()
{
myEngine hi();
hi.LoadSeq();
return 0;
}
I've not defined a constructor or destructor since they take no arguments right now and there aren't any member variable except a member function which returns nothing, just loads a file and prints to cout.
However trying to compile does not work:
rq12edu#env-12bw:~/Desktop/TestingBio++$ make
g++ main.cpp -o mainexec --static -I/local/yrq12edu/local/bpp/dev/include -L/local/yrq12edu/local/bpp/dev/lib -lbpp-seq -lbpp-core
main.cpp: In function 'int main()':
main.cpp:26:5: error: request for member 'LoadSeq' in 'hi', which is of non-class type 'myEngine()'
make: *** [all] Error 1
Maybe I'm being thick but I don't see why it's not letting me execute LoadSeq when I've defined it as a public member of myEngine, why is it erroring when it requests it from the hi instance of myEngine?
Thanks,
Ben W.

This:
myEngine hi();
declares a function, not an object. To declare and default-construct an object, remove the parentheses:
myEngine hi;

In this line:
myEngine hi();
You declare a function hi that returns instance of type myEngine.
Change it either to:
myEngine hi()
or
myEngine hi = myEngine();

This statement
myEngine hi();
is a function declaration with name hi having return type myEngine and no parameters.
Write instead
myEngine hi;
Or
myEngine hi {};
Take into account that you did not define the default constructor and the destructor (at least you did not show their definitions). That the code would ve compiled you couls define it the following way
class myEngine
{
public:
myEngine() = default;
~myEngine() = default;
//...
Or you could remove these declarations (and definitions) and use implicitly defined by the compiler constructor and destructor.

Related

No matching function for call to 'QuadBase::QuadBase'

I just started learning C++ for an Arduino project me and a friend have been working on. I'm getting the error "No matching function for call to 'QuadBase::QuadBase'" in main.cpp. I'not sure what is causing it, since I have the correct amount of arguments and they are the same type as well
edit: I brought it down to this and it still gives me that same error
#include <Arduino.h>
#include "QuadBase.h"
QuadBase base;
void setup()
{
base = QuadBase(
...
);
}
QuadBase.h
class QuadBase
{ public:
QuadBase( ... )
{
...
}
};
It seems your class QuadBase is missing a default constructor (one that takes no arguments) which is needed for the line
QuadBase base;

Pointer to member type incompatible with object type → What is the cause?

Recently I ran into a compiler (GNU g++ 4.9.2) error like this:
ProceduralTimerTaskAdapter.cpp:25:13: error: pointer to member type ‘void (Poco::Util::Timer::)(Poco::Util::TimerTask&)’ incompatible with object type ‘Poco::Util::ProceduralTimerTaskAdapter’
Here is the relevant code (which is almost self-contained, save for the necessary Poco libs):
ProceduralTimerTaskAdapter.h:
#include <Poco/Util/Timer.h>
#include <Poco/Util/TimerTask.h>
#include <Poco/Util/TimerTaskAdapter.h>
#ifndef PROCEDURALTIMERTASKADAPTER_H
#define PROCEDURALTIMERTASKADAPTER_H
using namespace std;
using namespace Poco::Util;
typedef void (*Callback) (TimerTask&);
namespace Poco {
namespace Util {
class ProceduralTimerTaskAdapter : public TimerTaskAdapter <Timer> {
public:
ProceduralTimerTaskAdapter (Callback procedure); // Constructor
void run (); // Method defining the main thread
protected:
~ProceduralTimerTaskAdapter (); // Destructor (not for general use)
private:
ProceduralTimerTaskAdapter (); // Default constructor (not for general use)
Callback procedure; // The callback procedure called by the timer.
};
}
}
#endif
ProceduralTimerTaskAdapter.cpp:
// This is the implementation of the ProceduralTimerTaskAdapter class.
#include <iostream>
#include <Poco/Util/Timer.h>
#include <Poco/Util/TimerTask.h>
#include <Poco/Util/TimerTaskAdapter.h>
#include "ProceduralTimerTaskAdapter.h"
using namespace std;
using namespace Poco::Util;
ProceduralTimerTaskAdapter::ProceduralTimerTaskAdapter (Callback procedure) : TimerTaskAdapter<Timer>::TimerTaskAdapter (*(new Timer ()), procedure)
{
this -> procedure = procedure;
}
ProceduralTimerTaskAdapter::~ProceduralTimerTaskAdapter ()
{
}
void ProceduralTimerTaskAdapter::run ()
{
TimerTask &task = *this;
(this ->* procedure) (task);
}
What I wanna do is, in fact, build an extension of the well-known TimerTaskAdapter to handle callback functions, which are not tied to a specific class (because they are situated in main.cpp, for instance). I override the virtual method run () with a very simple self-made one, which calls the callback. After having handled several different errors, I ended up with this apparent class mismatch I can't solve myself. I even don't understand why the compiler states a class name, whose name is Poco::Util::Timer:: (Why does it end with ::?). As ProceduralTimerTaskAdapter defines a member named procedure, why does the compiler expect another class?
Thank you.
Derive from Poco::Util::TimerTask (like in Poco::Util::TimerTaskAdapter class) and override run method in which you will call procedures.
class ProcedureAdapter : public Poco::Util::TimerTask {
public:
typedef void (*Callback)(TimerTask&);
ProcedureAdapter (Callback c) : callback(c) {;}
void run () {
callback(*this); // call some procedure which takes TimerTask
}
Callback callback;
};
void fun (Poco::Util::TimerTask&) {
cout << "fun was invoked" << endl;
}
void fun2 (Poco::Util::TimerTask&) {
cout << "fun2 was invoked" << endl;
}
int main()
{
Poco::Util::Timer t;
t.schedule (new ProcedureAdapter{&fun},1,1);
t.schedule (new ProcedureAdapter{&fun2},1,1);
The syntax ->* expects a left-hand operator of type pointer to class object (such as this) and a right-hand operator of type pointer to member function of that class. But in
TimerTask &task = *this; // line 24
(this ->* procedure) (task); // line 25
procedure is not a pointer to a member function of ProceduralTimerTaskAdapter. So your code is ill-formed. procedure is simply a pointer to a free (non-member) function taking a TimerTask& and returning void. If ProceduralTimerTaskAdapter is derived from
TimerTask then the following code should compile
TimerTask &task = *this;
(this -> procedure) (task);
or shorter
procedure(*this);
using the fact that pointers to functions can syntactically be used like the function.
Edit. It appears (from your comments to another answer) that your code was ill-formed in yet another way, namely that ProceduralTimerTaskAdapter was not derived from TimerTask. Then, of course already line 24 (not just 25) should produce an error. It seems, therefore, that you didn't show us the precise same code as the one that created the error message, or not all the errors it causes.

Classes included within main() method

If I have some code like
main(int argc, char *argv[])
{
...
#include "Class1.H"
#include "Class2.H"
...
}
Generally the main() method is the starting point of every application and the content within main() is to be executed. Am I right in the assumption that the content of all classes included into main() will be executed when main() is started?
greetings
Streight
No, no, NO.
First of all, you don't #include a file within a function. You #include a file at the beginning of a file, before other declarations. OK, you can use #include anywhere, but you really just shouldn't.
Second, #include doesn't execute anything. It's basically just a copy-paste operation. The contents of the #included file are (effectively) inserted exactly where you put the #include.
Third, if you're going to learn to program in C++, please consider picking up one of our recommended texts.
You commented:
I am working with the multiphaseEulerFoam Solver in OpenFoam and
inside the main() of multiphaseEulerFoam.C are classes included. I
assume that the classes have the right structure to be called in
main()
That may be the case, and I don't doubt that the classes have the right structure to be called from main. The problem is main will be malformed after the #includes because you'll have local class definitions and who knows what else within main.
Consider this. If you have a header:
foo.h
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo (const std::string& val)
:
mVal (val)
{
}
private:
std::string mVal;
};
#endif
And you try to include this in main:
main.cpp
int main()
{
#include "foo.h"
}
After preprocessing the #include directive, the resulting file that the compiler will try to compile will look like this:
preprocessed main.cpp
int main()
{
#ifndef FOO_H
#define FOO_H
class Foo
{
public:
Foo (const std::string& val)
:
mVal (val)
{
}
private:
std::string mVal;
};
#endif
}
This is all kinds of wrong. One, you can't declare local classes like this. Two, Foo won't be "executed", as you seem to assume.
main.cpp should look like this instead:
#include "foo.h"
int main()
{
}
#define and #include are just textual operations that take place during the 'preprocessing' phase of compilation, which is technically an optional phase. So you can mix and match them in all sorts of ways and as long as your preprocessor syntax is correct it will work.
However if you do redefine macros with #undef your code will be hard to follow because the same text could have different meanings in different places in the code.
For custom types typedef is much preferred where possible because you can still benefit from the type checking mechanism of the compiler and it is less error-prone because it is much less likely than #define macros to have unexpected side-effects on surrounding code.
Jim Blacklers Answer # #include inside the main () function
Try to avoid code like this. #include directive inserts contents of the file in its place.
You can simulate the result of your code by copy-pasting file content from Class1.H and Class2.H inside the main function.
Includes do not belong into any function or class method body, this is not a good idea to do.
No code will be executed unless you instantiate one of your classes in your header files.
Code is executed when:
Class is instantiated, then it's constructor method is called and the code inside the method is executed.
If there are variables of a class type inside your instantiated class, they will too run their constructors.
When you call a class method.
Try this example:
#include <iostream>
using namespace std;
int main()
{
class A
{ public:
A() { cout << "A constructor called" << endl; }
};
// A has no instances
class B
{ public:
B() { cout << "B constructor called" << endl; }
void test() { cout << "B test called" << endl; }
} bbb;
// bbb will be new class instance of B
bbb.test(); // example call of test method of bbb instance
B ccc; // another class instance of B
ccc.test(); // another call, this time of ccc instance
}
When you run it, you'll observe that:
there will be no instance of class A created. Nothing will be run from class A.
if you intantiate bbb and ccc, their constructors will be run. To run any other code you must first make a method, for example test and then call it.
This is an openFoam syntax he is correct in saying that open Foam treats #include like calling a function. In OpenFoam using #include Foo.H would run through the code not the class declaration that is done in a different hierarchy level. I would recommend all openFoam related question not be asked in a C++ forum because there is so much stuff built onto C++ in openFoam a lot the rules need to be broken to produce a working code.
You're only including declarations of classes. To execute their code, you need to create class instances (objects).
Also, you shouldn't write #include inside a function or a class method. More often than not it won't compile.

Using namespace for static class members

Can someone explain why the following code does not work? I cannot find any resources explaining the how namespaces, classes and identifiers fit together. When you do my_class::my_member, the my_class:: part is not a namespace? What is it?
#include <iostream>
class my_class {
public:
static void my_member() {
std::cout << "worked" << std::endl;
}
};
int main() {
using namespace my_class; // error: 'my_class' is not a namespace-name
my_member(); // error: 'my_member' was not declared in this scope
my_class::my_member(); // works
}
As a more general question: is there a way I can reference static class members without doing the my_class:: namespace/ identifier/ whatever each time?
Instead of
my_class::my_member_1
my_class::my_member_2
I just want
my_member_1
my_member_2
Is this possible? Thank you.
Is this possible?
Yes, indirectly. If you create a method that operates in my_class's scope, then you can get the behavior you want.
#include <iostream>
class my_class {
public:
static void my_member() {
std::cout << "worked" << std::endl;
}
static int my_main();
};
int my_class::my_main() {
my_member(); // no error
my_class::my_member(); // works too
return EXIT_SUCCESS;
}
int main() {
my_class::my_main();
}
my_class is not a namespace, it is a class name (a type). Therefore, you cannot use using namespace with my_class.
If you want to use my_member_1 without prefixing the class name, create a global wrapper function.
void my_member_1() {
my_class::my_member_1();
}
When you call a static function like this :
my_class::my_member();
You are refering to the class definition to find the static function. A static function will be the same for every instance of your class. You cannot access the static function either by simply calling the function name, or by creating an instance of the class to call the static function.
If you want to call directly the static function without writing down the class definition, you could do something like :
#define my_member_1 my_class::my_member_1()
#define my_member_2 my_class::my_member_2()
...
After that you could simply call my_member_1 to execute your static function, but that could get confusing on a large scale program. My advice is to keep using the class definition so you know exactly what function you are calling.

What if the default parameter value is defined in code not visible at the call site?

I've found some strange code...
//in file ClassA.h:
class ClassA {
public:
void Enable( bool enable );
};
//in file ClassA.cpp
#include <ClassA.h>
void ClassA::Enable( bool enable = true )
{
//implementation is irrelevant
}
//in Consumer.cpp
#include <ClassA.h>
....
ClassA classA;
classA.Enable( true );
Obviously since Consumer.cpp only included ClassA.h and not ClassA.cpp the compiler will not be able to see that the parameter has a default value.
When would the declared default value of ClassA::Enable in the signature of the method implementation have any effect? Would this only happen when the method is called from within files that include the ClassA.cpp?
Default values are just a compile time thing. There's no such thing as default value in compiled code (no metadata or things like that). It's basically a compiler replacement for "if you don't write anything, I'll specify that for you." So, if the compiler can't see the default value, it assumes there's not one.
Demo:
// test.h
class Test { public: int testing(int input); };
// main.cpp
#include <iostream>
// removing the default value here will cause an error in the call in `main`:
class Test { public: int testing(int input = 42); };
int f();
int main() {
Test t;
std::cout << t.testing() // 42
<< " " << f() // 1000
<< std::endl;
return 0;
}
// test.cpp
#include "test.h"
int Test::testing(int input = 1000) { return input; }
int f() { Test t; return t.testing(); }
Test:
g++ main.cpp test.cpp
./a.out
Let me admit first that this is the first time I have seen this type of code. Putting a default value in header file IS the normal practice but this isn't.
My guess is that this default value can only be used from code written in the same file and this way the programmer who wrote this wanted to put it in some type of easiness in calling the function but he didn't want to disturb the interface (the header file) visible to the outside world.
Would this only happen when the method
is called from within files that
include the ClassA.cpp?
That's correct. But note that doing so will almost certainly produce multiple definition errors, so the default is only really available from its point of definition within ClassA.cpp.
Put the default value in the declaration, not the definition.
class ClassA {
public:
void Enable( bool enable = true );
};