CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Apr 2005
    Posts
    7

    Getting a base class new instance

    Hello all,

    Suppose I have class B which inherits class A:

    Class A
    {
    dim x as integer
    }

    Class B
    inherits A
    {
    dim y as integer
    }

    I have an instance of class B, and I want to get from it an instance of class A with same property values. For example:

    dim b as new B
    b.x = 1
    b.y = 2
    dim a as A
    a = b.GET_BASE_CLASS_IN_SOME_WAY
    messagebox.show(a.x) //will show '1' in messagebox
    messagebox.show(a.y) //error - prohibited

    What can I do in the fifth line of code to get a reference to a ??
    Help will be fully appreciated, thanks

  2. #2
    Join Date
    Feb 2001
    Location
    Stamford CT USA
    Posts
    2,167

    Re: Getting a base class new instance

    Dim bObj As new B
    bObj.X = 1
    bObj.Y = 2

    Dim aObj As A = CType(bObj, A)
    or
    Dim aObj As A = DirectCast(bObj, A)
    Good Luck,
    -Cool Bizs

  3. #3
    Join Date
    Apr 2005
    Posts
    7

    Re: Getting a base class new instance

    It looks fine but a function I call that expects object of type A fail with the argument CType(b, A).

    When I look in debug Watch window I see that the type of the new instance I get from CType is actualy B.

    How can I make it work ?

  4. #4
    Join Date
    Feb 2001
    Location
    Stamford CT USA
    Posts
    2,167

    Re: Getting a base class new instance

    If your function expects type A, then you don't even have to do the conversion. You can pass in bObj directly into that function the FW will take care of the conversion.

    What exactly is the error message that you get?
    Good Luck,
    -Cool Bizs

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured