473,698 Members | 2,588 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

casting from base class to derive class

Can I cast from base class to derive class?

class A
{

}

class B:A
{

}

A a=new A();

B b=(B) a;

I get a cast exception.
Why?

Nov 17 '05 #1
2 1717
Locia <ro********@yah oo.it> wrote:
Can I cast from base class to derive class?
You can cast a base class type reference to a derived class type
reference, but at runtime the CLR will check that the object being
referred to as actually an instance of the derived class (or null).
class A
{

}

class B:A
{

}

A a=new A();

B b=(B) a;

I get a cast exception.
Why?


Because a *isn't* an instance of B.

Consider this code:

object x = new object();
FileStream y = (FileStream) x;

How on earth could the object actually behave like a FileStream? What
file would it be reading?

--
Jon Skeet - <sk***@pobox.co m>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
If replying to the group, please do not mail me too
Nov 17 '05 #2

"Locia" <ro********@yah oo.it> wrote in message
news:11******** *************@g 14g2000cwa.goog legroups.com...
Can I cast from base class to derive class?

class A
{

}

class B:A
{

}

A a=new A();

B b=(B) a;

I get a cast exception.
Why?

In simple terms, because inheritance works only from the general
(superclass) to the specific (subclass), not in the reverse direction.
Class B extends class A, thus all B objects are also A objects. However, the
reverse is not true. A objects are not objects of class B.
Giving the classes names makes it clearer. Let's call A Animal and B Mammal.
It's obvious that all mammals are animals, and just as obvious that all
animals are *not* mammals.

--
Peter [MVP Visual Developer]
Jack of all trades, master of none.
Nov 17 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
2333
by: Andy Lomax | last post by:
I'm using a library where the supplier has provided base class 'foo', and a reference counting class which wraps 'foo': ------------------- library code ----------------------- template<class T> refcount { ... // reference counting wrapper; like shared_ptr }; class foo {
2
1986
by: hswerdfe | last post by:
I have several Classes that derive from a common Base Class Each of these Classes Has a Differnt Version of a Function with the Same Short name, but different Long Name. See Bellow: // Base Class class CBase { void DoStuff(CBase* other);
3
1679
by: Kurt | last post by:
i just can't figure out why something im doing is not working correctly.... public interface IInterface { int someProperty { get; set; }
0
1307
by: Kurt Lange | last post by:
no... the array is created dynamically. and no... that defeats the purpose of what im trying todo.. encapsulate all initializing of variables in base class... derive from it... by deriving from base class, and casting, derived classes would already have their variables initialiezed(cause they have already been initialized in the base class) ....
8
2125
by: Michael | last post by:
Hi, I think my problem deals with class casting and inheritance. I want to deal with various Audio Formats, reading into memory for modification, working with it (done by different classes), and writing the result to disk afterwards. Therefore I have created some classes, e.g. WaveFileIO and AiffFileIO and MP3FileIO and AuFileIO for the In/Out operations.
6
1316
by: GarrettD78 | last post by:
Accidently posted this to the wrong group so I am reposting. This is probably a newbie question but I am a little confused about how to go next with my code. I think I want to use a factory pattern in this situation but I am having trouble getting access to properties at the presentation level. So my situation is I have a Vehicle base class. Public Class Vehicle Property BodyType as String End Class
6
1455
by: Spoon | last post by:
Hello everyone, I'm writing code where I can receive two kinds of packets. The first 12 octets are common to both packet types, i.e. they have the same semantics. The 1st type has 4 more octets in the header, then the payload. The 2nd type has 16 more octets in the header, then the payload. I was thinking I'd write a base class with two derived classes:
11
32406
by: Frederic Rentsch | last post by:
Hi all, If I derive a class from another one because I need a few extra features, is there a way to promote the base class to the derived one without having to make copies of all attributes? class Derived (Base): def __init__ (self, base_object): # ( copy all attributes ) ...
5
2191
by: Ronald Raygun | last post by:
If I have the following class heirarchy: class A{ protected $m_type; function type(){return $this->m_type;} } class B extends A{} class C extends B{}
0
8680
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8609
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9169
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9030
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
8871
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7738
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6528
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
1
3052
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2007
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.