I'm noob in C++, and I have the following header file (Header.h)
#ifndef HEADER_H
#define HEADER_H
#include <iostream>
using namespace std;
class Predicate
{
public:
virtual void print() = 0;
};
class UnaryIntegerPredicate : public Predicate
{
public:
virtual void print();
};
class BiaryIntegerPredicate : public Predicate
{
public:
virtual void print();
};
#endif
and in another separate .cpp file (Source.cpp), I tried to implement the print method, but got an "expected an expression" error.
#include "stdafx.h"
#include "Header.h"
#include <iostream>
using namespace std;
UnaryIntegerPredicate::UnaryIntegerPredicate() : Predicate()
{
virtual void print()
{
cout << "int : boolean" << endl;
}
}
what is wrong here, thanks!
I see you are probably coming from a Java background. What you need is
void UnaryIntegerPredicate::print()
{
cout << "int : boolean" << endl;
}
You don't need the stuff surrounding that. Since you have already declared in your header that UnaryIntegerPredicate derives from Predicate, you don't mention that again in the implementation file. You show that the print method that you are writing is the print method of the UnaryIntegerPredicate class by prefixing the name of the method with the name of the class as I have shown above.
You also don't need the virtual keyword in the cpp file because that is already specified in the header file.
Related
I got two classes separated in four files. The main class includes a sub class and needs to execute functions of it (not shown in the minimal example code). What I want to do is to execute a function of the main class in the scope of the subclass.
I think some ideas would be to inherit the functions in the sub class but I could not figure out how to do this.
MainClass.cpp
#include "MainClass.hpp"
void MainClass::mainCallback() {
std::cout << "[mainCallback] executed" << std::endl;
}
void MainClass::subCallback() {
std::cout << "[subCallback] executed" << std::endl;
}
int main() {
MainClass mainClass;
mainClass.mainCallback();
SubClass subClass;
subClass.activateSubClass();
return 0;
}
MainClass.hpp
#pragma once
#include "SubClass.hpp"
#include <iostream>
class MainClass{
public:
void mainCallback();
void subCallback();
};
SubClass.cpp
#include "SubClass.hpp"
void SubClass::activateSubClass(){
mainClass.subCallback(); //TODO call this function from this scope
}
SubClass.hpp
#pragma once
class SubClass{
public:
void activateSubClass();
};
The error in SubClass.cpp is of course:
error: use of undeclared identifier 'mainClass'
Just subclass the subclass:
class SubClass: public MainClass {
public:
void activateSubClass();
};
This (public) way the SubClass makes all methods of MainClass callable in SubClass instances. You could also private inherit. That way only activateSubClass() 'ld be callable.
In activateSubClass you can call directly the methods of the parent class:
void SubClass::activateSubClass(){
mainClass.subCallback(); //TODO call this function from this scope
}
Don't forget to include MainClass.hpp in SubClass.hpp
You try to call a MainClass.subCallback() without having an instance of MainClass. According to me, this is the typical use case for static methods.
Then, I think you make your #include directives the wrong way. Indeed, MainClass does not seem to need to know SubClass but the opposite is true. I think it is better to include MainClass.hpp in SubClass.hpp. This will solve your circle dependencies problem.And you can write your main() function in another file.
EDIT: Example
MainClass.hpp:
#pragma once
class MainClass
{
public:
void mainCallback();
static void subCallback(); // mak it static to be able to call it without an instance of the class
};
MainClass.cpp:
#include "MainClass.hpp"
#include <iostream>
void MainClass::mainCallback()
{
std::cout << "[mainCallback] executed" << std::endl;
}
void MainClass::subCallback()
{
std::cout << "[subCallback] executed" << std::endl;
}
SubClass.hpp:
#pragma once
class SubClass
{
public:
void activateSubClass();
};
SubClass.cpp:
#include "SubClass.hpp"
#include "MainClass.hpp" // MainClass inclusion
void Suclass::activateSubClass()
{
MainClass::subCallback(); // Call of the static method
}
main.cpp:
#include "MainClass.hpp"
#include "SubClass.hpp"
int main()
{
MainClass mc;
mc.mainCallback();
SubClass sc;
sc.activateSubClass(); // Will call MainClass::subCallback()
return 0;
}
I hope it can help you.
Like many people asking this question, I am very new to C++ and I can't wrap my head around this error:
Dollar.h:4:31: error: expected class-name before '{' token
class Dollar: public Currency {
These are my files
main.cpp
#include <iostream>
#include "Dollar.h"
using namespace std;
int main() {
Dollar * d = new Dollar();
d->printStatement();
return 0;
}
Currency.cpp
#include <iostream>
#include "Currency.h"
using namespace std;
class Currency {
public:
virtual void printStatement() {
cout << "I am parent";
}
};
Currency.h
#ifndef CURRENCY_H
#define CURRENCY_H
class Currency {
public:
virtual void printStatement();
};
#endif
Dollar.cpp
#include <iostream>
using namespace std;
void printStatement() {
cout << "I am dollar";
}
Dollar.h
#ifndef DOLLAR_H
#ifndef DOLLAR_H
class Dollar : public Currency {
public:
void printStatement();
};
#endif
Thank you so much for your time and any help is much appreciated.
The error says that the name of a class was expected between : public and { here:
class Dollar : public Currency {
^^^^^^^^
Currency is not a name of a class, because you haven't defined such class. Yes, you have defined such class in files Currency.cpp and Currency.h, but not in the file Dollar.h where that error occurs.
Solution: The class Currency has to be defined first before it can be used as a base class. Like so:
// class is defined first
class Currency {
public:
virtual void printStatement();
};
// now Currency is a class and it can be used as a base
class Dollar : public Currency {
public:
void printStatement();
};
Since a class must be defined in all source files where it is used, and the definition must be identical across all source files, it is often useful to define the class in a separate "header" file, such as you have done. In such case you can simply include that header in stead of writing the definition repeatedly in each source file:
#include "Currency.h"
Currency.cpp contains two definitions for the class Currency. Once in the header that is included, and then second time after that. You may not have multiple definitions for the same class in a single source file.
Solution: Remove the class definition from Currency.cpp. Instead only define the member function:
void Currency::printStatement() {
//...
}
Finally, you haven't defined Dollar::printStatement. You've defined printStatement, which is not the same thing.
In my case, I had two classes with same name but in two different namespaces.
So, changing the base class to something different solved the problem.
I would like to create a basic abstract class in C++, where the subclasses are each in a separate file. My abstract class looks something like
class Process_Base{
public:
virtual void process() = 0;
}
Should a simple implementation like this be contained entirely in a header file? If it is do I need to have a .cpp file associated with it?
When I create the subclasses what should their header file look? I was thinking .cpp file for the subclass should look something like
#include "Process_Base.h"
class Hello_Process : public Process_Base{
void process(){
printf("%s\n", "Hello, World");
}
}
Could someone verify that I am approaching this correctly, and if not give a simple example of what I should be doing.
UPDATE
I continued with the implementation but I am now getting the following compiler error
g++ -c -Wall -g Process_Message.cpp
Process_Message.cpp:4: error: expected class-name before ‘{’ token
The following is the abstract class header
// Abstract header .hpp file
class Process_Base{
public:
virtual void process() = 0;
};
the subclass header
// The subclass header .hpp file
#include "Process_Base.hpp"
class Process_Message : public Process_Base {
public:
void process();
};
and the implementation
// Simple implementation .cpp file
#include <stdio.h>
#include <string.h>
class Process_Message : Process_Base {
public:
void process(){
printf("%s", "Hello");
}
}
I don't understand why I am getting the error, can someone please explain.
You're missing ; at the end of Process_Base declaration, when you include the file, the compiler goes nut. correct is:
class Process_Base{
public:
virtual void process() = 0;
};
Why this 'Process_Base' is there in below code? You have already mentioned inheritance in header file,right?
// Simple implementation .cpp file
#include <stdio.h>
#include <string.h>
class Process_Message : Process_Base {
public:
void process(){
printf("%s", "Hello");
}
}
Also don't forget to type ';' at the end of the class declaration after '}'
Your correct code should look like this:
//Process_Message.h
#include "Process_Base.hpp"
class Process_Message : public Process_Base {
public:
void process();
};
//Process_Message.cpp
#include <stdio.h>
#include <string.h>
#include "Process_Message.h"
void Process_Message::process()
{
printf("%s", "Hello");
}
Don't forget to declare your overrides as virtual, or they will hide parent methods instead of implementing them.
#include <iostream>
class Process_Base
{
public:
virtual ~Process_Base() {}
virtual void process() =0;
};
class Process_Message : public Process_Base
{
public:
virtual void process(); // <- virtual
};
void Process_Message::process()
{
std::cout << "Hello";
}
The above should compile fine
I'm fairly new to c++ and I can't seem to find anyone else who has had the exact same problem as me. Basically, I'm trying to have an abstract class which I never directly instantiate, and several child classes. Also, I'm trying to keep a consistent template over all super/sub classes. Here's my source files. I have 3 utility files and one .cpp file for the main function.
abstract_matrix.h
#ifndef ABSTRACTMATRIX
#define ABSTRACTMATRIX
template<class T>
class DataMatrix {
public:
int numFeatures;
int numPoints;
T* data;
T* classifications;
virtual void scale(T scalar) = 0;
};
#endif
Here's my subclass declaration of that abstract class, sparse_host_matrix.h
#ifndef SPARSEHOSTMATRIX
#define SPARSEHOSTMATRIX
#include <iostream>
template<class T>
class SparseHostMatrix : public DataMatrix<T> {
public:
void scale(T scalar);
};
#endif
And here's the implementation of those functions..
#include "sparse_host_matrix.h"
#include <iostream>
template<class T>
void SparseHostMatrix<T>::loadFromFile(char* filename) {
std::cout << "Loading in sparseHostMatrix" << std::endl;
}
template<class T>
void SparseHostMatrix<T>::scale(T scalar) {
std::cout << "Loading in sparseHostMatrix" << std::endl;
}
And when I run this main function...
#include <iostream>
using namespace std;
#include "abstract_matrix.h"
#include "sparse_host_matrix.h"
int main() {
DataMatrix<double> *myMat = new SparseHostMatrix<double>;
myMat->scale(.5);
}
I get the error undefined reference to `SparseHostMatrix::scale(double)
Sorry for the massive amount of code, I'm just pretty confused and have been stuck on this for a while without successfully finding a solution on SO or otherwise.
Implementation of template functions must be in the header. You cannot place it in a separate source file. The compiler needs to see the actual body of the function at the point where it is used and actual template parameters become known.
I am trying to call another function, foo(), in the Raw class from main.cpp but I keep on getting this error and I do not understand what is wrong with my code. I am working in C++, and I am using the QT framework. I am new to this language and framework.
Error:
LNK2019: unresolved external symbol "public:void __thiscall RAW::foo(void)" (?foo#Raw##QAEXXZ) referenced in function_main. File not found:main.obj
main.cpp
#include "raw.h"
using namespace std;
int main(int, char*)
{
Raw newRaw;
newRaw.foo();
return 0;
}
raw.cpp
#include "raw.h"
#include <iostream>
using namespace std;
void foo()
{
cout << "hi\n";
}
Raw::Raw()
{
cout << "raw\n";
}
raw.h
#ifndef RAW_H
#define RAW_H
class Raw
{
public:
Raw();
void foo();
};
#endif // RAW_H
In raw.cpp you have to define foo like this:
void Raw::foo()
{
cout << "hi\n";
}
You have to put Raw:: so that the compiler knows that this is the class member function foo and not some other independent function.
As Mihai was saying, you can also define it in the Header file (.h/.hpp), but that is considered bad practice if your class method is complex in any way.
class Raw {
public:
void foo() {
cout << "hi\n";
}
};
Only time you should really ever do this is for extremely simple classes and for methods that are nothing more than getters really.
You should understand the difference between defining and declaring something in C++.
Declaring is to simply make a prototype, for example void doSomething(int); is a valid declaration as it says that the method doSomething takes an int and returns void.
Now, you need to describe what it does. This is the definition when you do void doSomething(int val) { cout << val << endl; } as you are now describing what to do with that function.
You can make the definition in the header file, as I showed, or in the source file (.c/.cpp) as Mihai showed (which is best practice). You can only make your declarations in the Header file, though.
Ok, this are some alternatives:
//raw.h
#ifndef RAW_H
#define RAW_H
class Raw
{
public:
Raw();
void foo(){cout << "raw\n";}
};
or
//raw.h
#ifndef RAW_H
#define RAW_H
class Raw
{
public:
Raw();
void foo();
};
Raw::Raw()
{
cout << "raw\n";
}
In both cases you won't need the implementation in raw.cpp anymore. But as I said before, my first solution is standard c++ practice.