473,698 Members | 1,996 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Casting Issue Correct Question! Sorry

Hi guys who just answered me.....it really would have helped if i had
written it right.

Ok i will use better names to explain my problem.

I have this:

InterFaceClass
^
ClassA
^
^
ClassB
ClassC
So i have an interface class that ClassA inherits from. ClassB and C then
inherit from classA.

i then want to do this:

ClassB myObj = (ClassB)some_Cl assA_Instance;

And i get a invalid cast. Why?
Oct 20 '06
14 1905
"Daniel" <Da*****@vestry online.comwrote in message
news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
Then i am confused again.

My class that was i was casting down to inherited and did not have any new
methods, just one inherited method that was overidden by implementation?
Why couldnt i cast?
Did you read the other thread to which I pointed you? If you haven't, go
back and do that now. I don't know if it will answer your question, but if
you haven't tried, there's no point in anyone making a further effort to
help.

I don't think you understand the difference between the class itself and an
instance of that class. As I posted earlier, the question of whether an
inherited class has new methods, new fields, overridden methods, etc. is
entirely irrelevant to the question of casting. Once you create an instance
of a class, its type is determined. No amount of casting will change that.
If the instance was not originally created as the more-derived type, you
cannot later cast it to that more-derived type.

Pete
Oct 20 '06 #11
"Daniel" <Da*****@vestry online.comwrote in message
news:%2******** ********@TK2MSF TNGP04.phx.gbl. ..
Ok i understand now.

What i dont get is this.

GenericAnimal g = (GenericAnimal) Dog;

yet if you look at g's type it remains Dog?? Why has it not become a
generic type?
Did you read the other thread I pointed you to?

The instance doesn't change type. Only the type of the reference *to* that
instance has changed. Casting it to GenericAnimal doesn't change the
instance...it just restricts your view of the instance to those things
within a GenericAnimal.

Sometimes I wonder if teaching people OOP with C# is such a great idea.
Ironically, because things are more abstracted in comparison to C++, the
difference between an object and a reference to that object are lost. I
suspect that if people had to distinguish between an instance and a pointer
to that instance (as they do in C++), these questions wouldn't come up
nearly as often as they do.

Anyway, back to the question: "g" is not the instance. It's a reference to
the instance. Likewise, "Dog" is not the instance, it's a reference to the
instance (that is, let's ignore that you made the same error you made
previously, using the name of a class rather than the name of an instance of
that class :) ). The type of the reference affects what of the instance you
can look at, but it doesn't change the instance itself. When you create a
new Dog, you are creating an instance. The variables that reference that
instance define the type used to view the instance, but not the type of the
instance itself.

Thus, the instance always keeps its original type. You can always cast
references to that type back and forth, as long as they remain consistent
with the type of the actual instance. IMHO, it's a mistake to think of
casting as being "up-cast" or "down-cast". In all cases, the casting is
just providing a new type through which to view the instance. The type cast
to must always be a type within the inheritance tree of the instance, and
will always either be the type of the instance itself, or an ancestor of
that instance's type (that is, a base class). But no matter what happens,
the validity of the cast is relative to the original instance, not the type
being cast from.

Pete
Oct 20 '06 #12
Daniel wrote:
Ok i understand now.

What i dont get is this.

GenericAnimal g = (GenericAnimal) Dog;

yet if you look at g's type it remains Dog?? Why has it not become a
generic type?
It is its generic, but it is also a Dog. So you could use g wherever a
GenericAnimal is called for and wherever a Dog is called for. But just
because you are treating it as a GenericAnimal doesn't mean it isn't still a
Dog. A Dog is a GenericAnimal, and this specific instance of a
GenericAnimal is a Dog, but not all GenericAnimals are Dogs.
--
Tom Porterfield

Oct 20 '06 #13
Daniel <Da*****@vestry online.comwrote :
Then i am confused again.

My class that was i was casting down to inherited and did not have any new
methods, just one inherited method that was overidden by implementation? Why
couldnt i cast?
Just because it doesn't have any new methods or fields doesn't mean you
can cast from one form to the other. It's not the right type, that's
all there is to it.

--
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
Oct 20 '06 #14
Ok great

Thanks guys i fully understand now.

i am one of these people that doesn't like a 'vague' understanding, i keep
asking questions until i feel i understand 100% which i do now. I think it
is my c++ background haunting me and it has taken a while to adjust to the
no pointer scenario.

Thanks for all the replies and patience.
"Tom Porterfield" <tp******@mvps. orgwrote in message
news:%2******** ********@TK2MSF TNGP03.phx.gbl. ..
Daniel wrote:
>Ok i understand now.

What i dont get is this.

GenericAnima l g = (GenericAnimal) Dog;

yet if you look at g's type it remains Dog?? Why has it not become a
generic type?

It is its generic, but it is also a Dog. So you could use g wherever a
GenericAnimal is called for and wherever a Dog is called for. But just
because you are treating it as a GenericAnimal doesn't mean it isn't still
a Dog. A Dog is a GenericAnimal, and this specific instance of a
GenericAnimal is a Dog, but not all GenericAnimals are Dogs.
--
Tom Porterfield

Oct 20 '06 #15

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

Similar topics

231
23133
by: Brian Blais | last post by:
Hello, I saw on a couple of recent posts people saying that casting the return value of malloc is bad, like: d=(double *) malloc(50*sizeof(double)); why is this bad? I had always thought (perhaps mistakenly) that the purpose of a void pointer was to cast into a legitimate date type. Is this wrong? Why, and what is considered to be correct form?
35
2685
by: ytrama | last post by:
Hi, I have read in one of old posting that don't cast of pointer which is returned by the malloc. I would like to know the reason. Thanks in advance, YTR
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) ....
7
3676
by: yufufi | last post by:
lets say we have a 'shape' class which doesn't implement IComparable interface.. compiler doesn't give you error for the lines below.. shape b= new shape(); IComparable h; h=(IComparable)b; but it complains for the following lines
24
2458
by: pinkfloydhomer | last post by:
Is it well-defined to make a cast from a pointer to an int and back? Like: typedef struct { int whatever; } S; int main(void) {
3
3651
by: Beta What | last post by:
Hello, I have a question about casting a function pointer. Say I want to make a generic module (say some ADT implementation) that requires a function pointer from the 'actual/other modules' that takes arguments of type (void *) because the ADT must be able to deal with any type of data. In my actual code, I will code the function to take arguments of their real types, then when I pass this pointer through an interface function, I...
24
39150
by: AtariPete | last post by:
Hey All, I have a C# question for you regarding up casting (base to derived). I was wondering about the most elegant way (readable, less code) to cast from a base type to its derived type. Please consider the following two classes: class Base { private int m_valA;
1
2867
by: Jay Hamilton | last post by:
Hello, I am running into an invalid address alignment error on an HPUX box when I attempt to lookup a value in a STL map. The argument being passed in is a double, which is accessed from a structure; the map's key is also a double. The issue seemed to be occuring in the map's default comparison function so I implemented my own comparison operator, but then the error continued happening in my new fxn. Strangely, casting the double I...
19
1947
by: =?Utf-8?B?WWFua2VlIEltcGVyaWFsaXN0IERvZw==?= | last post by:
I'm doing my c# more and more like i used to code c++, meaning i'm casting more often than creating an instance of objects. like : protected void gvOrderDetailsRowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { switch (((Sale)e.Row.DataItem).SzPN) {
0
8674
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
9157
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
9027
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...
1
8895
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
7725
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...
0
5860
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4369
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
2329
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2001
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.