Problem with abstract classes

  • Thread starter Thread starter Fergal Moran
  • Start date Start date
F

Fergal Moran

Hello Guys

I'm a C++ programmer moving to C# and I'm trying to do something which
I regularly do in C++ and am wondering why it doesn't work in C#.

Basically in C++ I can do something similar to the following

class A{
public:
virtual void foo()=0;
};

class B : public A{
public:
virtual void foo()=0;
};

class C : public B{
public:
virtual void foo(){
cout << "Test";
}
};

Where class B and A are abstract classes with a pure virtual function
"foo"

If I try the equivalent in C#

public abstract class A {
public abstract void foo();
}
public abstract class B : A {
public abstract void foo();
}
public class C : B {
public override void foo() {
return "Hello Sailor";
}
}

I get....

error CS0533: 'B.foo()' hides inherited abstract member 'A.foo()'
error CS0534: 'C' does not implement inherited abstract member
'A.foo()'

Is this inheritance structure not valid in C# or am I missing
something.

Regards,

Fergal
 
"Fergal Moran" <[email protected]> a écrit dans le message de (e-mail address removed)...

| Basically in C++ I can do something similar to the following
|
| class A{
| public:
| virtual void foo()=0;
| };
|
| class B : public A{
| public:
| virtual void foo()=0;
| };
|
| class C : public B{
| public:
| virtual void foo(){
| cout << "Test";
| }
| };
|
| Where class B and A are abstract classes with a pure virtual function
| "foo"
|
| If I try the equivalent in C#
|
| public abstract class A {
| public abstract void foo();
| }
| public abstract class B : A {
| public abstract void foo();
| }
| public class C : B {
| public override void foo() {
| return "Hello Sailor";
| }
| }
|
| I get....
|
| error CS0533: 'B.foo()' hides inherited abstract member 'A.foo()'
| error CS0534: 'C' does not implement inherited abstract member
| 'A.foo()'
|
| Is this inheritance structure not valid in C# or am I missing
| something.

You are not quite getting the syntax right. you don't need to redeclare the
abstract method in B.

public abstract class A
{
public abstract void foo();
}

public abstract class B : A
{
}

public class C : B
{
public override void foo()
{
return "Hello Sailor";
}
}

Joanna
 
You are completely correct Joanna thanks a lot - I also could have used

public override abstract string foo();

in class B - which to appears a bit closer to what I am used to...

Thanks for the reply

Fergal.
Glad no-one noticed a void function returning a string :)
 
Back
Top