Calling an Interface function from multiple different implementing classes c++ - c++

Hi I am trying to implement an interface in C++. I want to be able to call a function from a class that could be implemented by various different classes. The approach I have tried fails since I cannot call the function with a pointer to the interface (abstract class). Here is the basic gist of the code I have tried:
Interface class:
class InterfaceClass{
virtual void handle() = 0;
};
Calling class:
CallingClass::CallingClass(InterfaceClass * owner){
this->owner = owner;
}
void CallingClass::doStuff(){
owner->handle();
}
Implementing classes:
class Class1 : public InterfaceClass {
public:
Class1();
void handle();
}
class Class2 : public InterfaceClass {
public:
Class2();
void handle();
}
each of the handle() functions in the implementing classes just prints out the class name. Each implementing class contains an object of the CallingClass which calls doStuff in a separate timer thread. I am trying to keep it so that the CallingClass doesnt need to know anything about the classes that implement the handle() function.
It fails since I cannot call the function of an abstract class. I expected this but cant figure a way around it. Any advise would be much appreciated! Let me know if any more information is needed.
Thanks

you were missing the public: keyword in the Interface class.
you need to remember that C++ class are by default private, so you should add public where it is needed.
this is a working example for you:
class InterfaceClass {
public:
virtual void handle() = 0;
};
class Calling{
public:
Calling(InterfaceClass * owner) {
this->owner = owner;
}
void doStuff() {
owner->handle();
}
~Calling() { delete owner; }
private :
InterfaceClass* owner;
};
class Class1 : public InterfaceClass {
public:
void handle() override
{
std::cout << "Class1"<<std::endl;
}
};
class Class2 : public InterfaceClass {
public:
void handle()
{
std::cout << "Class2" << std::endl;;
}
};
int main(int argc, char** argv)
{
Calling c1(new Class1());
c1.doStuff();
Calling c2(new Class2());
c2.doStuff();
}

Related

Is there a better design practice than to add a new virtual function in base that is not implemented by all derived classes

I have class hierarchy as shown below. It's a simplified version of actual code.
class Base
{
public :
// user_define_type is a output parameter
virtual void Fill(user_define_type);
}
class A : public Base
{
public :
void Fill(user_define_type) override;
}
class B : public Base
{
public :
void Fill(user_define_type) override;
}
I am overriding Fill() method as I need different formatting in both derived classes. Now I have to write one more class deriving from "Base" as it has common functionality. Now my problem is that new class will have to implement Fill() that will operate on different user defined type. As I am returning base class pointer from factory so new Fill() has to be virtual in base but that means I have to add it's definition in older classes "A" and "B" and throw not supported exception from them. This is not a good design. Any better design you guys can suggest ? Thanks in advance.
I believe you need to create a common base class for your user_defined_types in order to achieve this. I also think this could be a good place to use the strategy pattern.
Basically, you create
class user_defined_type_base
{
...
}
class user_defined_type_derived : public user_defined_type_base
{
...
}
class DoSomething
{
private:
DoSomethingStrategy *strategy;
public:
DoSomething(DoSomethingStrategy *strategy) { this->strategy = strategy; }
void Fill(user_defined_type_base *type) { this->strategy->Fill(type); }
}
class DoSomethingStrategy
{
public:
virtual void Fill(user_defined_type_base *obj) = 0;
}
class DoSomethingStrategyA : public DoSomethingStrategy
{
public:
void Fill(user_defined_type_base *obj)
{
...
}
}
class DoSomethingStrategyB : public DoSomethingStrategy
{
public:
void Fill(user_defined_type_base *obj)
{
...
}
}
class DoSomethingStrategyC : public DoSomethingStrategy
{
public:
void Fill(user_defined_type_base *obj)
{
...
}
}
void main()
{
DoSomethingStrategy *strategy = new DoSomethingStragegyA();
DoSomething *dosomething = new DoSomething(strategy);
user_defined_type_base *type = new user_defined_type_base();
dosomething->Fill(type);
DoSomethingStrategy *strategyC = new DoSomethingStragegyC();
DoSomething *dosomethingC = new DoSomething(strategyC);
user_defined_type_base *typeC = new user_defined_type_derived();
dosomethingC->Fill(typeC);
}

C++. Why I can't implement interface using trait class?

So I want to use a trait class to implement my contract class, is it possible? Because I got some errors when I compile this following code:
code:
class MyContract {
public:
virtual void foo()=0;
};
class TraitClass {
public:
void foo()
{
Serial.println("hello");
}
};
class MyClass : public virtual MyContract, public TraitClass {
// MyClass stuff here.
};
void setup()
{
MyClass* myClass = new MyClass();
myClass->foo();
}
MyClass does not implement the pure virtual method declared in the MyContract superclass. Just because it also inherits from TraitClass doesn't mean that TraitClass's foo() is going to implement it.
You need to connect the dots:
class MyClass : public virtual MyContract, public TraitClass {
void foo() override
{
TraitClass::foo();
}
};

Accessing base class methods from a subclassed nested class

The question extends this question
The situation is the following. I'm extending a virtual method of a inner class:
class ClassOne {
public:
class InnerClass {
public:
virtual void method1();
protected:
friend class ClassOne
};
protected:
oftenUsedMethod();
private:
friend class InnerClass;
};
void ClassOne::InnerClass::method1()
{
#Do stuff with oftenUsedMethod();
}
class SubClassOne : public ClassOne {
class DerivedInnerClass : InnerClass {
virtual void method1();
};
};
void SubClassOne::DerivedInnerClass::method1()
{
##I need the access to the oftenUsedMethod???
}
Here is an image to try to clarify the problem :)
InnerClass uses ofthenUsedMethod() in its methods, and has access to it. To be able to extend the methods, I need access to ofthenUsedMethod() in DerivedInnerClass. Can this be achieved?
There are two problems to overcome:
Inner classes, by default, are not associated with an instance of the outer class, sou you'll have to make this dependency explicit by giving it a pointer to the outer class. If you do this, you'll need to be careful that instances of the inner class don't outlive the object they are referring to.
The derived inner class is not derived from the outer class so it does not have access to its protected members. What you can do is add a protected function into InnerClass that calls the function. This function is a member of InnerClass and derived classes can call it. Dynamic binding will do the rest.
Here is the above in C++:
#include <iostream>
class ClassOne
{
protected:
virtual void
oftenUsedMethod()
{
std::clog << "ClassOne::oftenUsedMethod()" << std::endl;
}
class InnerClass
{
private:
/** Pointer to an instance of the outer class. */
ClassOne *const outer_;
public:
InnerClass(ClassOne *const outer) : outer_ {outer}
{
}
protected:
virtual void
method1()
{
std::clog << "ClassOne::InnerClass::method1()" << std::endl;
this->dispatch();
}
/**
* Simply calls the protected member of the outer class.
* Derived classes can therefore access it indirectly, too.
*
*/
void
dispatch()
{
// Be aware: If *this->outer_ has already been destructed
// (and there is no simple way for us to tell whether it has),
// calling a member function on it will cause disaster.
this->outer_->oftenUsedMethod();
}
};
};
class SubClassOne : public ClassOne
{
protected:
virtual void
oftenUsedMethod() override
{
std::clog << "SubClassOne::oftenUsedMethod()" << std::endl;
}
class DerivedInnerClass : public ClassOne::InnerClass
{
DerivedInnerClass(ClassOne *const outer) : InnerClass {outer}
{
}
protected:
virtual void
method1() override
{
std::clog << "SubClassOne::DerivedInnerClass::method1()" << std::endl;
this->dispatch();
}
};
};
The override is a C++11 feature, you don't need it but it makes your intention clear.

Virtual function call

Here is my hierarchic of classes.
I have declare following abstract interface class, which have just one function:
class IAuthenticator
{
public:
virtual void CreateJson() = 0;
};
After I have created on more class 'UIData' and inherits it from interface class, in this case:
class UIData : public IAuthenticator
{
protected:
UIData() : mWindowHandle(0)
{ /* Constructor do nothing. **/ }
private:
integer mWindowHandle;
public:
void CreateJson()
{
std::cout<<"UIData::CreateJson\n";
}
};
I have one more class which inherits from UIData
class AuthenticateIn : public UIData
{
private:
string mOrigin;
string mLogoURL;
string mUserID;
public:
void CreateJson()
{
std::cout<<"AuthenticateIn::CreateJson\n";
}
};
Question
In my main function I have write code like this.
int main()
{
AuthenticateIn* ai = new AuthenticateIn();
ai->CreateJson();
}
When I call CreateJson() function I see log "AuthenticateIn::CreateJson". I want to find a way to call CreateJson() and it will be called for all base classes.
I know that I can do that calling this->UIData::CreateJson() from AuthenticateIn class CreateJson function, but is there any other way to do that, some automatic way ? Thanks !!
is there any other way to do that, some automatic way
No, there isn't. You have to call the base class's implementation from the derived class. The compiler won't do this automatically since it doesn't know whether you actually want this.
You have to call the base class function in the derived class sort of like this:
void CreateJson() {
UIData::CreateJSon();
}
etc
No, there is no such way. If you want to call virtual function from base class you should do this directly.
You may not be able to force a call to a virtual base class, but you can use indirection to simulate the behaviour.
typedef int integer;
#include <iostream>
#include <string>
using std::string;
using std::cout;
class IAuthenticator
{
public:
virtual void CreateJson() = 0;
};
class UIData : public IAuthenticator
{
protected:
UIData() : mWindowHandle(0)
{ /* Constructor do nothing. **/ }
private:
integer mWindowHandle;
virtual void CreateJsonPrivate() = 0;
public:
void CreateJson()
{
CreateJsonPrivate();
std::cout<<"UIData::CreateJson\n";
}
};
class AuthenticateIn : public UIData
{
private:
string mOrigin;
string mLogoURL;
string mUserID;
virtual void CreateJsonPrivate()
{
std::cout<<"AuthenticateIn::CreateJson\n";
}
};
int main()
{
AuthenticateIn* ai = new AuthenticateIn();
ai->CreateJson();
}
Output:
AuthenticateIn::CreateJson
UIData::CreateJson

unexpected invoke copyWithZone c++ cocos2d

I have some trouble.
I made some interface (abstract class in c++). Implemented it in my class (derived from CCObject too).
In third class I try to invoke method of interface and got SIGABORT. Here the code
//interface class
class CallBackInterface
{
public:
virtual void SomeMethod() = 0;
};
//my class that implement the interface
class MyClass : public CallBackInterface, public CCObject
{
public:
void SomeMethod(){/*some realization*/};
};
//class that invoke the SomeMethod
class CallBacker()
{
public:
CallBackInterface* callBackObject;
};
//main code
CallBacker* callBacker = new CallBacker();
MyClass* myClass = new MyClass();
callBacker->callBackObject = myClass;
/*
this string generate unexpected invoke of copyWithZone method CCObject's class
with SIGABORT. */
callBacker->callBackObject->SomeMethod();
/*
In debugger mode I see that SomeMethod don't invoke (debugger don't go into it). Here the copyWithZone*/
CCObject* CCCopying::copyWithZone(CCZone *pZone)
{
CC_UNUSED_PARAM(pZone);
CCAssert(0, "not implement"); <<- here is SIGABORT
return 0;
}
The copyWithZone invokation crashes my app
class CallBackInterface : public CCObject
{
public:
virtual void SomeMethod() = 0;
};
class MyClass : public CallBackInterface
{
void SomeMethod(){}
};
Try this! I met the same problem before.