Cornel Verster
Cornel Verster

Reputation: 1781

Implementing this Abstract Class using a declaration

I'm implementing the Automatak opendnp3 libraries for c++. I want to add a Master to a Channel.As you can see from this definition, a parameter for this action is:

...
opendnp3::IMasterApplication& appliction,
...

The IMasterApplication interface is described here. So I create masterApplication.cpp and masterApplication.h files and attempt to implement the class as follows:

masterApplication.cpp

 #include "masterApplication.h"

 #include <opendnp3/master/IMasterApplication.h>

 #include <iostream>
 #include <chrono>

 using namespace opendnp3;
 using namespace asiodnp3;
 using namespace std;

 masterApplication::masterApplication() {
    }

 masterApplication::~masterApplication() {
    }

masterApplication.h

#ifndef MASTERAPPLICATION_H_
#define MASTERAPPLICATION_H_

 #include <opendnp3/master/IMasterApplication.h>
 #include <opendnp3/link/ILinkListener.h>
 #include <openpal/executor/IUTCTimeSource.h>

 class masterApplication : public opendnp3::IMasterApplication
 {
 private:

 public:
    masterApplication();
    virtual ~masterApplication();
 };

 #endif

But, when I try to declare a masterApplication object in my main to use:

masterApplication iMaster;

And then place that within the AddMaster function, I get the error:

main.cpp:57:20: error: cannot declare variable ‘iMaster’ to be of abstract type ‘masterApplication’
   masterApplication iMaster;

What am I misunderstanding here?

Upvotes: 0

Views: 128

Answers (2)

CinCout
CinCout

Reputation: 9619

As mentioned in the comment, whenever implementing an abstract class (interface), all the pure virtual methods that are part of the abstract class must be defined (provided with a body) in the derived class. Then only the derived class becomes concrete, and can be used as a type. Otherwise it also becomes abstract.

"So does the declaration of a method make it non-abstract?"

Not the declaration, but the definition. Methods are already declared (as pure virtual) in the base class (interface). Giving them definition (body) in the derived class makes the derived class non-abstract (concrete).

"Also, do I just have to declare it in masterApplication without actually using it? "

You need to define all the pure virtual methods of the base class in the derived class. Use them or not will depend on your use-case.

Upvotes: 3

BlackDwarf
BlackDwarf

Reputation: 2070

To complete HappyCoder's answer:

Taking a look at the opendnp3::IMasterApplication, you can see that it inherits from both opendnp3::ILinkListener and opendnp3::IUTCTimeSource.

While the first doesn't have any pure virtual method, here is the code of the second (source):

class IUTCTimeSource
{

public:
    virtual UTCTimestamp Now() = 0;
};

Then you need to overload the function Now() in your class masterApplication in order to make it non-abstract.

Upvotes: 3

Related Questions