Why C++ compiler (gcc) thinks function is `virtual' field? - c++

I have a the following method definition in my class:
virtual Calc* Compile(
Evaluator* evaluator, ResolvedFunCall* fun_call, string* error);
For some reason, GCC complains that:
error: 'Compile' declared as a 'virtual' field
Any ideas why it would believe Compile to be a field, instead of a method?

I get that error when the first parameter doesn't make sense to it. Check that Evaluator is known as type:
struct A {
virtual void* b(nonsense*, string*);
};
=> error: 'b' declared as a 'virtual' field
struct A {
virtual void* b(string*, nonsense*);
};
=> error: 'nonsense' has not been declared
To find out whether something is a object or function declaration, the compiler sometimes has to scan the whole declaration. Any construct within the declaration that could possibly form a declaration is taken to be a declaration. If not, then any such construct is taken to be an expression. GCC apparently thinks because nonsense is no valid type, it can't be a valid parameter declaration, and thus falls back treating the whole declaration as a field (note that it says in addition error: expected ';' before '(' token ) . Same thing in local scope
int main() {
int a;
// "nonsense * a" not treated as declaration
void f(nonsense*a);
}
=> error: variable or field 'f' declared void
int main() {
// "nonsense * a" treated as parameter declaration
typedef int nonsense;
void f(nonsense*a);
}
=> (compiles successfully)

This happened to me when I declared a virtual function with {} instead of ().
A sample to demonstrate the error:
test.h
class Test{
public:
Test(){}
~Test(){}
//next line is defective, use () instead of {}
virtual int myfunct{int i};//notice brackets here which causes the error
};
test.cpp
#include "test.h"//i omitted include guards for simplicity
int Test::myfunct(int x){
x=5;
return x;
}
main.cpp
#include "test.h"
int main(){
Test test;
return 0;
}

Related

"Incomplete type not allowed " when creating std::ofstream objects

Visual Studio Throws this Strange Error:
Incomplete type not allowed
When I try to create an std::ofstream object. Here is the code I wrote inside a function.
void OutPutLog()
{
std::ofstream outFile("Log.txt");
}
whenever it encounters this Visual Studio throws that Error. Why This Happens?
As #Mgetz says, you probably forgot to #include <fstream>.
The reason you didn't get a not declared error and instead this incomplete type not allowed error has to do with what happens when there is a type that has been "forward declared", but not yet fully defined.
Look at this example:
#include <iostream>
struct Foo; // "forward declaration" for a struct type
void OutputFoo(Foo & foo); // another "forward declaration", for a function
void OutputFooPointer(Foo * fooPointer) {
// fooPointer->bar is unknown at this point...
// we can still pass it by reference (not by value)
OutputFoo(*fooPointer);
}
struct Foo { // actual definition of Foo
int bar;
Foo () : bar (10) {}
};
void OutputFoo(Foo & foo) {
// we can mention foo.bar here because it's after the actual definition
std::cout << foo.bar;
}
int main() {
Foo foo; // we can also instantiate after the definition (of course)
OutputFooPointer(&foo);
}
Notice we could not actually instantiate a Foo object or refer its contents until after the real definition. When we only have the forward declaration available, we may only talk about it by pointer or reference.
What is likely happening is you included some iostream header that had forward-declared std::ofstream in a similar way. But the actual definition of std::ofstream is in the <fstream> header.
(Note: In the future be sure to provide a Minimal, Complete, Verifiable Example instead of just one function out of your code. You should supply a complete program that demonstrates the problem. This would have been better, for instance:
#include <iostream>
int main() {
std::ofstream outFile("Log.txt");
}
...also, "Output" is generally seen as one complete word, not two as "OutPut")

C++: Defining void* array in header file and declaring it in a cpp file?

I saw this question and I tried to do as the answer to that question said. To use the extern keyword in the header file to define an array and then declare it outside of that namespace or class in a other cpp file.
It didn't work for me really, I'm not sure if it because I'm using a void pointer array (i.e void* array[]) or if it's just my ignorance that prevents me from seeing the problem.
This is the shortest example I can come up with:
[cpp.cpp]
#include "h.h"
void main(){
void* a::b[] = {
a::c = a::d(1)
};
}
[h.h]
namespace a{
struct T* c;
struct T* d(int e);
extern void* b[];
}
So the problem is that I receive the error:
IntelliSense: variable "a::b" cannot be defined in the current scope
And I have no clue why that is.
First, you should declare main() as int ! See here why.
Declaring your array as extern in a namespace means that it belongs to the namespace but is defined somewhere ele, normally in a separate compilation unit.
Unfortunately, in your main(), you try to redefine the element as a local variable. This explains the error message you receive.
You shoud do as follows:
#include "h.h"
void* a::b[] { a::c, a::d(1) }; // global variable belonging to namespace
int main() // int!!!
{
/* your code here */
}
The code will compile. The fact that a::b[] is defined in the same compiling unit is accepted. But the linker will complain because a::d(1) is a call to the function d returning a pointer to a struct, and this function is defined nowhere.
Therfore you should also define this:
namespace a {
struct T* d(int e)
{
return nullptr; // in reality you should return a pointer to struct T
}
}
Interestingly, struct T does not need to work for this code to compile and link.

C++ syntax help, using templates

It is probably some stupid syntax mistake, i have the following class written in h file
#include "IGenticSolverHelper.h"
template <class T>
class GenericGeneticSolver
{
public:
GenericGeneticSolver(IGenticSolverHelper<T>& helper, int generationSize) : mSolverHelper(helper)
{
mSolverHelper.GenerateFirstGeneration(0, generationSize, currentGeneration);
}
private :
vector<T> currentGeneration;
IGenticSolverHelper<T>& mSolverHelper;
};
And then the following code :
#include "IGenticSolverHelper.h"
#include "GenericGeneticSolver.h"
class HelperImpl : IGenticSolverHelper<int>
{
public:
void GenerateFirstGeneration(const int seed,const int generationSize, vector<int>& firstGeneration)
{
}
void Crossover(const int& father,const int& mother, int& son)
{
}
void Mutate(const int& orignal, int& mutated)
{
}
float Cost(int& solution)
{
}
};
int main()
{
int a =5;
GenericGeneticSolver<int> mySolver(HelperImpl,a);
}
And i get the following error when i compile :
error C2061: syntax error : identifier 'a'
if i will change the line to :
GenericGeneticSolver<int> mySolver(HelperImpl);
it will compile, though the constructor expect 2 arguments, and will get the following warning :
warning C4930: 'GenericGeneticSolver<T> mySolver(HelperImpl)': prototyped function not called (was a variable definition intended?)
And to add to the oddness, when i put a break point on this line, he won't stop there.
What am i doing wrong, i just trying to create an instance of GenericGeneticSolver
Take a look at this line:
GenericGeneticSolver<int> mySolver(HelperImpl,a);
The compiler is confused about what you're trying to do here because HelperImpl is the name of a type, while a is the name of an object. The compiler thinks what you're doing is trying to prototype a function named mySolver that takes in a parameter of type HelperImpl and a parameter of type a, but then gets stuck because it doesn't know of any types named a.
If you remove a, you get this:
GenericGeneticSolver<int> mySolver(HelperImpl);
This is a perfectly legal prototype of a function called mySolver that takes an argument of type HelperImpl and returns a GenericGeneticSolver<int>. The warning you're getting is the compiler telling you that you might not have meant to make this a prototype, since it somewhat looks like an instantiation of a variable named mySolver but isn't.
Since I assume that you're trying to instantiate an object of type GenericGeneticSolver<int> here, you probably want to instantiate a HelperImpl and then pass that object into the constructor, like this:
HelperImpl hi;
GenericGeneticSolver<int> mySolver(hi, a);
Hope this helps!

Structure As constructor parameter (Declared in main)

I have the following structure declared in main (NEVERMIND THE MEMBERS!) :
struct args
{
std::vector<string> names;
std::vector<std::shared_ptr<RegularExpression>>vreg;
std::vector<string> stopFile;
std::vector<string> groundTruth;
int debug;
};
and I have a classe Verification that takes args as a constructor parameter
#ifndef VERIFICATION_H
#define VERIFICATION_H
class Verification
{
public:
Verification(std::string, std::vector<double>,double,args);
private:
args _A;
}
#endif // VERIFICATION_H
Now in main:
struct args
{
std::vector<string> names;
std::vector<std::shared_ptr<RegularExpression>>vreg;
std::vector<string> stopFile;
std::vector<string> groundTruth;
int debug;
};
int main()
{
Verification v("res.cr",gt, 0.75,A);
return 0;
}
I have the following compile errors :
Verification.h|33|error: 'args' does not name a type| (this error is for the private member in the class _A)
main.cpp|153|error: no matching function for call to 'Verification::Verification(const char [7], std::vector&, double, args&)'|
Verification.h|24|error: 'args' has not been declared|(this error is the constructor)
How can I use the structure declared in main as a constructor parameter in class verification?
Thank you.
The structure must be defined in a way that it is visible to the Verification class translation unit. I suggest you move the struct to its own header file, and #include that in your main file and in Verification.h.
The first error is that when compiling class Verification the compiler must see struct args first. It doesn't know that you are gonig to define struct args later.
Simple fix would be to move the definition of struct args into Verification.h.
Fix that and you'll still have other errors though (most obviously that there's no definition for A), but we can deal with those when you get to them.
Your second error is due to the fact that a string literal is a const char[], not a std::string- you need to create a string before passing it to a function expecting a string.
Also, gt and A need to be defined before this call.

Exception Handling C++ error

#include<iostream>
#include<stdlib.h>
#include<string.h>
using namespace std;
class div
{
int x,y;
public:
class dividebyzero
{
};
class noerror1
{
};
div(){};
div(int a,int b)
{
x=a;
y=b;
}
void error1()
{
if(y==0)
throw dividebyzero();
else
throw noerror1();
}
int divide()
{
return (x/y);
}
};
class naming
{
char name[32];
public:
class nullexception
{
};
class noerror2
{
};
naming(char a[32])
{
strcpy(name,a);
}
void error2()
{
if(strcmp(name,"")==0)
throw nullexception();
else
throw noerror2();
}
void print()
{
cout<<"Name-----"<<name<<endl;
}
};
int main()
{
div d(12,0);
try
{
d.error1();
}
catch(div::dividebyzero)
{
cout<<"\nDivision by Zero-------Not Possible\n";
}
catch(div::noerror1)
{
cout<<"\nResult="<<d.divide()<<endl;
}
naming s("Pankaj");
try
{
s.error2();
}
catch(naming::nullexception)
{
cout<<"\nNull Value in name\n";
}
catch(naming::noerror2)
{
s.print();
}
return 0;
}
On compiling this program I am getting following error
pllab55.cpp: In function ‘int main()’:
pllab55.cpp:61:6: error: expected ‘;’ before ‘d’
pllab55.cpp:64:3: error: ‘d’ was not declared in this scope
pllab55.cpp:72:22: error: ‘d’ was not declared in this scope
pllab55.cpp:74:20: warning: deprecated conversion from string constant to ‘char*’ [-Wwrite-strings]
Before declaring the class naming everything was running fine.It is after declaration of naming these error started to occur. I am new to C++. Please explain me in details. Thanks in advance.
There is already an std::div in the standard namespace and since you use a using namespace directive instead of declaration it imports all the symbols in std namespace to your current scope. So perhaps renaming the div class shall do the trick for you.
I tried renaming it and it does work indeed.
So either rename your class or wrap it in your own namespace so it does not conflict with std::div
Your class div shares the same name as std::div. When you do #using namespace std, the result is that each class in the std namespace is imported into your current scope, meaning that std::div is now essentially called div. If you see, that means you now have two classes called div in the same scope, your own and the std class.
By the way, you should avoid the using namespace syntax and rather use the full qualifier of the class (e.g. std::cout).
Your div class is conflicting with std::div so either rename yours or put put your div class in a different namespace.
namespace me {
struct div{};
}
me::div d;
I gave (a slight variant of) your code a try in gcc and I got the following error:
/usr/include/stdlib.h:780: error: too few arguments to function 'div_t div(int, int)'
You're trying to override a name from a standard library and experience the conflict of a class and a function having the same name, I'm afraid.
as a general rule of thumb, if you encounter such issues, try to reduce your code as much as possible. For instance, I reduced it down to
#include<stdlib.h>
class div {
public:
div (int a, int b) { }
};
int
main () {
div d (12, 0);
return 0;
}
which still shows your error (at least the first one - the others are followup errors).
This lets you also reduce possible assumptions about the reason for the error - as you see, your new class "naming" does not have to do anything with the error you see.
When I now additionally remove the include, the error does not show up anymore, which lets me suspect some naming clash with some symbol from stdlib.h. After renaming the class "div" to something else (like "CDiv"), it works.