views:

283

answers:

1

I have a class which inherits from another and I want to make use of one of the base class functions...but I am running into a problem where calling the base function does not return the member variable from the inherited class as I had hoped.

To illustrate my problem, I have created a simplified example. I expected this example to output "5" but it doesn't :) The solution seems to be that I need to copy the getInt() function from myclass1 into myclass2 too...then it will work, but this seems to defeat the point of inheriting from myclass1 (I wanted to avoid duplicating the function in each class).

class Program
{
    static void Main(string[] args)
    {
        myclass2 myclass = new myclass2();

        // Expected to output 5, but it actually outputs 0
        Console.WriteLine( myclass.getInt() );
    }
}

struct s1
{
    public string str;
    public int num;
}

struct s2
{
    public int num;
    public int num2;
}

class myclass1
{
    internal s1 mystruct;

    internal int getInt()
    {
        return mystruct.num;
    }
}

class myclass2 : myclass1
{
    internal new s2 mystruct;

    internal myclass2()
    {
        mystruct.num = 5;
    }
}
+4  A: 

You are hiding myclass1.mystruct with myclass2.mystruct. They are two completely different objects.

You can override the object by making it virtual in the base class and override in the subclass, but the object has to keep its type. You can't change the type of an instance, because that's not type-safe. (FIXME) If you want to change the type of mystruct, why?

If you just want to access myclass1.mystruct from myclass2 you can use base.mystruct, I think.

strager
Yes strager is right. Instead can you just make it protected in the base class and not declare+initialize a new one, just set it, as if its protected and class2 inherits it, it should have access, i don't think you'll want the internal.
David
Thanks guys - unfortunately the type of mystruct needs to be different in both classes. The overall project is a wrapper around some C++ API's and the API is versioned with two different structs representing the same thing. The XP version of the struct has different contents to the Vista version and my code needs to be agnostic to OS. I've tried to simplify this scenario into the example above.Is there any way to get this working without just copying the getInt() function into myclass2? (it seems like there is no point to keep inheriting at that stage)
@DaveUK, Can you be more specific with your problem? Is each 'myclass' an OS? Wouldn't you have a "base" OS class then several OS-specific subclasses?
strager