Thread: Issue with abstract classes

  1. #1
    l'Anziano DavidP's Avatar
    Join Date
    Aug 2001
    Location
    Plano, Texas, United States
    Posts
    2,743

    Issue with abstract classes

    I am using a library of code which has some classes defined like such:

    Code:
    public abstract class A
    {
    ...stuff...
    }
    
    public class B : A
    {
    ...stuff...
    }
    So we have a class A and a class B which inherits from A. Class A is also abstract.

    Now, we then have some function somewhere in the code which declares an instance of class B, does some operations on that object, and then returns it to the caller. It, however, returns it as if it were an instance of class A. It is something like this:

    Code:
    public A ReturnInstanceOfA()
    {
    	B myobj = new B();
    	return B;
    }
    Now, as a client to this library, I would like to call this function which instantiates an object of class B and returns it to me, and I want to see it as being a B and not an A. So I do this:

    Code:
    B myobj = ReturnInstanceOfA() as B;
    Problem. I get this error: Cannot convert type 'A' to 'B' via a reference conversion, boxing conversion, unboxing conversion, wrapping conversion, or null type conversion


    How can I solve this issue?
    Last edited by DavidP; 08-18-2008 at 02:46 PM.
    My Website

    "Circular logic is good because it is."

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    That compiles just fine for me, the problem lies elsewhere. Are you sure your code doesn't try to cast like this?
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Issue with pointers to an abstract class and inheritance
    By bainevii in forum C++ Programming
    Replies: 2
    Last Post: 03-31-2009, 07:51 AM
  2. Operators of abstract classes
    By Thanuja91 in forum C++ Programming
    Replies: 1
    Last Post: 11-02-2007, 05:30 AM
  3. Abstract classes
    By cisokay in forum C++ Programming
    Replies: 17
    Last Post: 05-29-2005, 09:39 AM
  4. Replies: 7
    Last Post: 03-10-2004, 04:10 PM
  5. Purpose of Abstract Classes
    By luckygold6 in forum C++ Programming
    Replies: 15
    Last Post: 04-29-2003, 06:24 PM