implimenting interface function by inheriting from other class
Tejas
notrealemail at gmail.com
Sun Aug 22 05:20:34 UTC 2021
On Sunday, 22 August 2021 at 01:14:08 UTC, Alexey wrote:
> On Saturday, 21 August 2021 at 20:35:43 UTC, Alexey wrote:
>> Hello
>> ```D
>> interface Int
>> {
>> void coolFunc();
>> }
>>
>> class C1
>> {
>> void coolFunc()
>> {
>> return;
>> }
>> }
>>
>> class C2 : C1, Int
>> {
>>
>> }
>>
>> void main()
>> {
>> auto c = new C2;
>> }
>> ```
>> dmd says it's not Ok:
>> t.d(14): Error: class `t.C2` interface function `void
>> coolFunc()` is not implemented
>>
>> how to make dmd happy?
>
> we're with friends tried similar thing with c++, java, groovy
> and go - worked ok.
> ```Java
> interface Int
> {
> public void coolFunc();
> };
>
> class C1
> {
> public void coolFunc()
> {
> return;
> }
> };
>
> class C2 extends C1 implements Int
> {
>
> };
>
>
> public class Main {
>
> public static void main(String args[])
> {
> Int c = new C2();
> }
>
> }
> ```
> ```Groovy
> interface Int
> {
> void coolFunc()
> }
>
> class C1
> {
> void coolFunc()
> { print "hello" }
> }
>
> class C2 extends C1 implements Int
> { }
>
> def printHello = { Int a -> a.coolFunc(); print " world: accept
> $Int" }
>
> C2 a = new C2()
> printHello(a)
> ```
> ```C++
> class Int;
> class C1;
> class C2;
>
> class Int
> {
> public:
> virtual void coolFunc() = delete;
> };
>
> class C1
> {
> public:
> virtual void coolFunc()
> {
> return;
> }
> };
>
> class C2 : public C1, public Int
> {
> public:
> };
>
> int main(int argc, char* argv[])
> {
> auto c = new C2;
> }
> ```
> ```Go
> package main
>
> import "fmt"
>
> type Int interface {
> CoolFunc()
> }
>
> type C1 struct {
> }
>
> func (self *C1) CoolFunc() {
> fmt.Println("worked")
> return
> }
>
> type C2 struct {
> C1
> }
>
> func main() {
>
> var c Int
>
> c = new(C2)
>
> c.CoolFunc()
>
> }
> ```
Sorry, Bastiaan's solution is the only that I know of as well.
Here's your desired behaviour:
```d
import std.stdio:writeln;
interface Int
{
void coolFunc();
}
class C1
{
void coolFunc()
{
{
auto obj = (cast(C1)(cast(Int) this));
if (obj !is null)
{
do_one_thing();
}
}
{
auto obj = (cast(C2)(cast(Int) this));
if (obj !is null)
{
obj.do_another_thing();
}
}
{
auto obj = (cast(C3)(cast(Int) this));
if (obj !is null)
{
obj.do_something_else();
}
}
return;
}
void do_one_thing(){
writeln("one thing from C1");
}
}
class C2 : C1, Int
{
override void coolFunc(){
typeof(super).coolFunc();
}
void do_another_thing(){
writeln("did another thing from C2");
}
}
class C3 : C1, Int
{
override void coolFunc(){
typeof(super).coolFunc();
}
void do_something_else(){
writeln("doing something else from C3");
}
}
class C4 : C1, Int
{
override void coolFunc(){
typeof(super).coolFunc();
}
}
void main()
{
auto c = new C2;
c.coolFunc();
}
```
More information about the Digitalmars-d-learn
mailing list