I'm writing a cross-platform class hierarchy, and want to keep the platform dependent implementations in their own class (as opposed to having one class with #ifdefs). This is what I have so far, but the compiler is complaining that BaseDef is private. Any help with how I could keep this basic structure while getting it to compile would be greatly appreciated :-)
Edit: It would seem from here that this isn't possible. Any other way I could keep this general structure and still compile?
Root.h
class Root {
private:
class BaseDef {
virtual void foo() = 0;
virtual void bar() = 0;
};
#ifdef _WIN32
class WinImp;
#else
class NixImp;
#endif
BaseDef* imp;
BaseDef* getImp();
public:
Root() : imp(getImp()) {}
void foo();
void bar();
};
Root.cpp
#include "Root.h"
void Root::foo() {
imp->foo();
}
void Root::bar() {
imp->bar();
}
WinImp.h
#ifdef _WIN32
#include "Root.h"
class WinImp : public Root::BaseDef {
public:
void foo();
void bar();
};
#endif
WinImp.cpp
#include "WinImp.h"
#ifdef _WIN32
Root::WinImp::foo() {
}
Root::WinImp::bar() {
}
Root::BaseDef* Root::getImp() {
return new Root::WinImp();
}
#endif
Your main problem is that BaseDef is private. That means that other classes (aside from Root itself) cannot access the BaseDef name. One way is to make BaseDef public. Alternatively you can make the derived classes (WinImp and NixImp) friends of Root so that they can access the BaseDef name. In addition Root cannot access the members of BaseDef so they need to be public or make Root a friend of BaseDef.
class Root {
private:
class BaseDef {
public:
// These need to be public so that Root can see them or Root needs to be a friend.
//Nothing else can see BaseDef though so this is safe.
virtual void foo() = 0;
virtual void bar() = 0;
};
class WinImp; // Forward declare the classes
friend class WinImp; // And then make them friends
class NixImp;
friend class NixImp;
BaseDef* imp;
BaseDef* getImp();
public:
Root() : imp(getImp()) {}
void foo();
void bar();
};
void Root::foo() {
imp->foo();
}
void Root::bar() {
imp->bar();
}
// Since this is a nested class i made it Root::WinImp
class Root::WinImp : public Root::BaseDef {
public:
void foo();
void bar();
};
void Root::WinImp::foo() {}
void Root::WinImp::bar() {}
Root::BaseDef* Root::getImp() {
return new WinImp();
}
This method is not allowed according to the 2003 standard (11.4.p2) but in C++11 (same example) it is explicitly allowed (11.3.p2). However, clang (3.1 tested) accepts this even in 2003 mode. gcc (4.7.2 tested) accepts this (even in 2003 mode) so long as the derived classes are nested inside the same class but not if outside the class.
It's complaining that BaseDef is private...
class Root {
private:
class BaseDef {
virtual void foo() = 0;
virtual void bar() = 0;
};
So make it public...
class Root {
public:
class BaseDef {
virtual void foo() = 0;
virtual void bar() = 0;
};
Footnote:
You're trying to avoid #ifdef, so get rid of this:
#ifdef _WIN32
class WinImp;
#else
class NixImp;
#endif
Instead, just use a single class:
class Imp;
Related
I am no doubt overlooking something basic but my implementation is obviously flawed.
I am trying to require a derived classes to implement a method being called in a base class.
class IClock
{
public:
virtual void OnTimeExpired() = 0;
}
class Clock : public IClock
{
... // ABC not implemented
}
class Application : public Clock
{
... // ABC not implemented
}
class DerivedApp : public Application
{
public:
virtual void OnTimeExpired() { ... }
}
I rarely use pure ABCs, so I thought by not defining the pure virtual method in Clock and Application, it would require all derivatives of Application to define the OnTimeExpired() method.
I discovered this will compile and link (MSVS-2017) and if DerivedApp does not implement the method, the Clock object will call an undefined method and crash.
Why does this compile without the pure virtual method being implemented?
How do I force derived Application classes to implement the OnTimeExpired() method?
EDIT: The crash was due to unrelated error - I apologize. Nevertheless the questions I ask are still applicable.
As requested here is a complete, buildable, minimal example:
IClock.h:
#pragma once
class IClock
{
public:
virtual void OnClockTime() = 0;
};
Clock.h:
#pragma once
#include "IClock.h"
class Clock : public IClock
{
public:
Clock();
virtual ~Clock();
void ClockUpdate();
virtual void OnClockTime();
private:
float elapsed_time;
};
Clock.cpp:
#include "Clock.h"
Clock::Clock()
: elapsed_time(0.0f)
{
}
Clock::~Clock()
{
}
void Clock::ClockUpdate()
{
elapsed_time += 0.0000001f; // small ticks for testing
if (elapsed_time >= 1.0f) {
OnClockTime();
elapsed_time -= 1.0f;
}
}
void Clock::OnClockTime()
{}
ApplicationBase.h
#pragma once
#include "Clock.h"
class ApplicationBase : public Clock
{
public:
ApplicationBase();
virtual ~ApplicationBase();
virtual void Init(){}
virtual void Run(){}
protected:
bool app_run;
};
ApplicationBase.cpp:
#include "ApplicationBase.h"
ApplicationBase::ApplicationBase()
: app_run(false)
{
}
ApplicationBase::~ApplicationBase()
{
}
DerivedApp.h:
#pragma once
#include "ApplicationBase.h"
class DerivedApp : public ApplicationBase
{
public:
DerivedApp();
virtual ~DerivedApp();
virtual void Init() {}
virtual void Run();
//virtual void OnClockTime();
};
DerivedApp.cpp:
#include "DerivedApp.h"
#include <iostream>
DerivedApp::DerivedApp()
{
}
DerivedApp::~DerivedApp()
{
}
void DerivedApp::Run()
{
app_run = true;
while (app_run) {
ClockUpdate();
}
}
//void DerivedApp::OnClockTime()
//{
// static int counts(0);
// std::cout << "Tick..." << std::endl;
// counts++;
// if (counts >= 10)
// app_run = false;
//}
main.cpp
#include "DerivedApp.h"
class App : public DerivedApp
{
public:
App(){}
~App(){}
};
int wmain(int argc, wchar_t * argv[])
{
App *app = new App();
app->Init();
app->Run();
delete app;
}
Thanks to those who requested a minimal working example, I built it and it works exactly as I had hoped. The complier will complain about no instantiation of the ABC in the App class. If I remove the comments from DerivedApp::OnClockTime() it compiles and runs the way I wish. Obviously my actual code is not following this model as I thought, so now I need to reexamine where I went wrong. Thanks.
There is no keyword in C++ that forces a class to override some method. However, by making OnTimeExpired() pure virtual you're making IClock an abstract class. Any classes deriving from IClock that do not implement OnTimeExpired() will automatically become an abstract class too, thus not allowing you to create objects of these classes. This means that your code as-is is completely legal unless you try to make objects of these classes
class AbstractBase {
public:
virtual void someFunc() = 0; // Purely Virtual
};
class AbstractDerived : public AbstractBase {
public:
void someOtherFunc();
// Still abstract because the following is not declared-defined
// void someFunc() override { ... }
};
class NonAbstractDerivedA : public AbstractBase { // Derived From Base
public:
void someFunc() override { /* do this class's implementation*/ }
};
class NonAbstractDerivedB : public AbstractDerived { // Derived From AbstractDerived
public:
void someFunc() override { /* do this class's implementation*/ }
};
uses:
#include "above"
int main() {
AbstractBase base; // compiler error
AbstractDerived derived; // compiler error
NonAbstractDerivedA derivedA; // should be okay
NonAbstractDerivedB derivedB; // should be okay
return 0;
}
Override is quite informative keyword. However, one can use it in class declaration only. Is there any reason to forbid its use in definitions? Example:
class Base
{
public:
virtual void Method() = 0;
};
class Child : public Base
{
public:
void Method() override;
};
// source.cpp
void Child::Method() override // oops
{
...
}
At the moment, I have a parent class and 2 child classes declared in Setplay.h, as such
namespace agent {
class Setplay {
public:
virtual int reset() {return 0;};
};
class ChildSetplay1 : public Setplay {
public:
virtual int reset();
};
class ChildSetplay2 : public Setplay {
public:
virtual int reset();
};
}
And in a Setplay.cpp, I define the methods
namespace agent {
int ChildSetplay1::reset(){
return 1;
}
int ChildSetplay2::reset(){
return 2;
}
}
Is there a way to avoid re-declaring the methods in the .h and still define unique methods for each child?
If I avoid re-declaring the methods in the .h:
namespace agent {
class Setplay {
public:
virtual int reset() {return 0;};
};
class ChildSetplay1 : public Setplay {};
class ChildSetplay2 : public Setplay {};
}
Then I get the following error:
error: no ‘int agent::ChildSetplay1::reset()’ member function declared in class ‘agent::ChildSetplay1’
But I can't define different methods for each child if I change the methods' signature to something like
int reset(){
return ??; // return 1? 2?
}
I'm not sure there is a way to do this, but my motives are:
the actual classes have several methods and re-declaring everything all the time looks ugly
I still need to keep everything inside the .cpp and .h
So, is it possible? Or are there better alternatives?
You need to define the function for every child, so you can't escape this. What you can do, is to go a little bit around and use a #define if you have multiple functions
Like:
#define SET_PLAY_FUNCTIONS public:\
virtual int reset();\
virtual int go();
namespace agent {
class Setplay {
public:
virtual int reset() {return 0;};
virtual int go();
};
class ChildSetplay1 : public Setplay {
SET_PLAY_FUNCTIONS
};
class ChildSetplay2 : public Setplay {
SET_PLAY_FUNCTIONS
};
}
At least you can save something.....
I would like to have a C++ Interface that must be overridden (if this is possible) when inherited. So far, I have the following:
class ICommand{
public:
// Virtual constructor. Needs to take a name as parameter
//virtual ICommand(char*) =0;
// Virtual destructor, prevents memory leaks by forcing clean up on derived classes?
//virtual ~ICommand() =0;
virtual void CallMe() =0;
virtual void CallMe2() =0;
};
class MyCommand : public ICommand
{
public:
// Is this correct?
MyCommand(char* Name) { /* do stuff */ }
virtual void CallMe() {}
virtual void CallMe2() {}
};
I have purposely left how I think the constructor/destructor's should be implemented in ICommand. I know if I remove the comments, it will not compile. Please could someone:
Show me how to declare the constructor/destructor's in ICommand and how they are meant to be used in MyCommand
Have I set things up correctly in ICommand so that MyCommand must override CallMe and CallMe2.
C++ does not allow for virtual constructors. A simple implementation (without the virtual constructor) would look something like this:
class ICommand {
public:
virtual ~ICommand() = 0;
virtual void callMe() = 0;
virtual void callMe2() = 0;
};
ICommand::~ICommand() { } // all destructors must exist
Note that even a pure virtual destructor must be defined.
A concrete implementation would look exactly like your example:
class MyCommand : public ICommand {
public:
virtual void callMe() { }
virtual void callMe2() { }
};
You have a couple of options for the constructor. One option is to disable the default constructor for ICommand, so that subclasses will have to implement a constructor that calls your ICommand constructor:
#include <string>
class ICommand {
private:
const std::string name;
ICommand();
public:
ICommand(const std::string& name) : name(name) { }
virtual ~ICommand() = 0;
virtual void callMe() = 0;
virtual void callMe2() = 0;
};
ICommand::~ICommand() { } // all destructors must exist
A concrete implementation would now look something like this:
class MyCommand : public ICommand {
public:
MyCommand(const std::string& name) : ICommand(name) { }
virtual void callMe() { }
virtual void callMe2() { }
};
I know this one is old, but it is still my first hit on this issue. This is how I would do it.
Interface header foo.h:
#pragma once
#include <memory>
enum class Implementations {Simple, Fancy};
class Foo
{
public:
using Ptr = std::unique_ptr<Foo>;
virtual ~Foo() = default;
virtual void do_it() = 0;
};
Foo::Ptr create_foo(Implementations impl); // factory
Yes I know that "pragma once" is strictly speaking not standard, but it works for me.
Note that nothing is implemented here. There is no constructor: an abstract class can not be instantiated. You get a pointer to the interface through the factory. For the virtual function calls to work, they must be called through a pointer. The virtual destructor is defaulted because it doesn't have to do anything special except polymorphing to the implementation. The factory is a free function. No need to try to make it a static member or something like that. This is not java.
Interface foo.cpp:
#include "foo.h"
#include "foo_impl.h"
Foo::Ptr create_foo(Implementations impl)
{
switch (impl)
{
case Implementations::Simple:
return std::make_unique<Simple_foo>();
case Implementations::Fancy:
return std::make_unique<Fancy_foo>();
default:
return nullptr;
}
}
Here the factory is implemented. Notice that the factory has to know the implementation(s). That is why we don't implement it inline: if it was inline, the interface header would have to include the implementation header, and through it, knowledge of the implementation would "leak out" to the callsite.
The implementation header foo_impl.h:
#pragma once
#include "foo.h"
class Simple_foo : public Foo
{
void do_it() override;
};
class Fancy_foo : public Foo
{
void do_it() override;
};
Nothing special, just override the virtual functions of the interface. Because this exaple is simple, I put both implementations in the same files. In real applications that will be different.
The implementation foo_impl.cpp:
#include "foo_impl.h"
#include <iostream>
void Simple_foo::do_it()
{
std::cout << "simple foo\n";
}
void Fancy_foo::do_it()
{
std::cout << "fancy foo\n";
}
Just implement the functions.
The main.cpp:
#include "foo.h"
int main()
{
auto sf = create_foo(Implementations::Simple);
sf->do_it();
auto ff = create_foo(Implementations::Fancy);
ff->do_it();
return 0;
}
Through the enum we can select the implementation we want. The pointers are of type Foo::Ptr, an alias for std::unique_ptr<Foo>. The callsite has no knowledge of the implementation at all, only the interface.
The output will be as expected:
simple foo
fancy foo
I have a problem creating some form of hierarchy with different object types. I have a class which has a member of another class, like this:
class A
{
public:
A(){}
~A(){}
void addB(B* dep){
child = dep;
dep->addOwner(this);
}
void updateChild(){
child->printOwner();
}
void print(){
printf("Printing...");
}
private:
B* child;
};
And this is class B:
class B
{
public:
void addOwner(A* owner){
ownerObject = owner;
}
//ISNT WORKING
void printOwner(){
ownerObject->print();
}
private:
A* ownerObject;
};
Calling a function of "B" out of class "A" works just fine but trying it vice versa gives a compiler error because A is not defined in B. It actually is by using an include and a forward declaration, but I guess its a cross reference problem which the compiler can not solve.
Is there any chance to solve this problem or should I rethink my design?
You say that you already solved your circular dependency problem by using a forward declaration of A instead of including the header where A is defined, so you already know how to avoid circular includes. However, you should be aware of what is possible and what is not with incomplete types (i.e. types that have been forward declared).
In your case, you try to call the member function print on an object that has an incomplete type; the compiler knows nothing about this type excepts that it will be defined at some point, so it does not allow you to do this. The solution is to remove the implementation of the printOwner member function from the B header and put it into an implementation file:
//B.hpp
class A; // forward declaration
class B
{
public:
void addOwner(A* owner);
void printOwner() const; // I think this member function could be const
private:
A* ownerObject;
};
//B.cpp
#include "B.hpp"
#include "A.hpp" // here we "import" the definition of A
void B::addOwner(A * owner)
{
ownerObject = owner;
}
void B::printOwner() const
{
ownerObject->print(); //A is complete now, so we can use its member functions
}
You could possibly do the same thing in the A header.
You can use forward declaration, and define the member functions outside of the class, i.e.
// A.h
class B;
class A { public:
void addB(B* dep); // don't define addB here.
...
};
// B.h
class A;
class B { public:
void addOwner(A* owner); // don't define addOwner here.
...
};
// A.cpp
#include "A.h"
#include "B.h"
void A::addB(B* dep) {
...
}
// B.cpp
// similar.
You probably should rethink your design, since a crcular parent-child relationship is usually a code smell.
But, you can make the compiler happy :
#include <cstdlib>
#include <cstdio>
class A
{
public:
A(){}
~A(){}
void addB(class B* dep);
void updateChild();
void print(){
printf("Printing...");
}
private:
class B* child;
};
class B
{
public:
void addOwner(A* owner){
ownerObject = owner;
}
//ISNT WORKING
void printOwner(){
ownerObject->print();
}
private:
A* ownerObject;
};
void A::addB(class B* dep){
child = dep;
dep->addOwner(this);
}
void A::updateChild(){
child->printOwner();
}
int main()
{
return 0;
}
You should move B::printOwner implementation to .cpp file.