I'm fairly confident in C and Java and just started using C++, still getting used to the basics about best practices including data abstraction (which, as far as I understand, means proper header usage).
I'd like to make a project that solves different types of problems that all imply reading data from a file, solving the problem and writing the result to a new file, so I figured I'd use something similar to an interface in Java.
My header looks like this:
#include <iostream>
using namespace std;
class Problem {
public:
/*
* Read data from file.
*/
virtual bool read(string filename) = 0;
/*
* Solve problem.
*/
virtual void solve() = 0;
/*
* Write solution to file.
*/
virtual bool write(string filename) = 0;
};
class Brothers : public Problem {};
I'm trying to implement the first function in my Brothers.cpp
source file like this:
bool Brothers::read(string filename) override {...}
Which, save for the Brothers::
part, is how I would normally implement this function if I had just source files.
I'm getting the errors Function 'read' was not declared in class 'Brothers'
and Function doesn't override any base member functions
, and I would like to understand why this approach isn't working and what I should do instead.
Even though you are overriding the base class declaration, unlike in java, you will still need to declare the function in the derived class's header file. The compiler only looks in the class associated with that function, so when you say that there is a function read
in Brother
and it can't see that there is one explicitly, you get an error.
Another thing is that when you use interfaces or other abstract classes, everything that is declared as pure virtual has to be defined before there is a class that is not pure virtual, so in this example:
class A
{
virtual void foo() = 0;
}
class B : public A
{
virtual int bar()
{
return 0;
}
}
class C : public B
{
virtual void foo()
{
// Do something
}
}
Class A
is abstract because it has a pure virtual function, but so is B
because it still has no definition for foo()
. Until there is a definition for it, there can be no non-abstract classes.