473,387 Members | 3,750 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Casting up to inheriting class from base?

Say I have a class inheriting some base class:

BaseClass
{
void Foo()
{
Update();
}
}
Class1 : BaseClass
{
void Update(){}
}
How can I have the base class know which instance class has inherited
it and use a method in the instance class? Only certain types of
classes will use the base and those classes will always have an
Update() method.

Thanks,
Brett

Jul 6 '06 #1
10 1716
One way of doing this is to use an interface implemented in the
inheriting class. In the base, do this:

(( IMyClass )this).Update();

I'm interested in any better methods.

Thanks,
Brett

Jul 6 '06 #2

Brett Romero wrote:
Say I have a class inheriting some base class:

BaseClass
{
void Foo()
{
Update();
}
}
Class1 : BaseClass
{
void Update(){}
}
How can I have the base class know which instance class has inherited
it and use a method in the instance class? Only certain types of
classes will use the base and those classes will always have an
Update() method.
Maybe I'm missing something, but why can't you just make the base class
abstract, like this:

abstract BaseClass
{
void Foo()
{
Update();
}

abstract void Update()
{ ... }
}

?

Jul 6 '06 #3
Hi Brett,
I am curious why you have Foo( ) in BaseClass if Update( ) might not
exist to be called? Would it just make more sense to put Foo( ) in the
subclass? It seems like you might want to reconsider your design --
otherwise you are getting into "downcasting" (casting from a baseclass
to a derived class). Usually when I run into that, I take it as a hint
that it's time to refactor the code...

Also, what will Foo( ) do if it determines that the derived class does
not implement Update( ) ? If it just does nothing, then maybe you
should have a virtual Update( ) in the BaseClass that simply does
nothing, then override that function in the subclass.

Not that I'm recommending this, but to answer your question you can
always use the "is" keyword to check what type you're dealing with.
For example:

class Base
{
public void Foo()
{
if (this is Derived)
{
Derived d = (Derived)this;
d.Update();
}
}
}

class Derived : Base
{
public void Update()
{
Console.WriteLine("I am derived");
}
}

class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
d.Foo(); // prints "I am derived"

Base b = new Base();
b.Foo(); // prints nothing
}
}

Hope that helps,
John

Brett Romero wrote:
One way of doing this is to use an interface implemented in the
inheriting class. In the base, do this:

(( IMyClass )this).Update();

I'm interested in any better methods.

Thanks,
Brett
Jul 6 '06 #4
Bruce is right - make Update an abstract method of BaseClass.

--
Adam Clauss
Jul 6 '06 #5

"Brett Romero" <ac*****@cygen.comwrote in message
news:11**********************@m38g2000cwc.googlegr oups.com...
Say I have a class inheriting some base class:

BaseClass
{
void Foo()
{
Update();
}
}
Class1 : BaseClass
{
void Update(){}
}
How can I have the base class know which instance class has inherited
it and use a method in the instance class? Only certain types of
classes will use the base and those classes will always have an
Update() method.
It's hard for me to say for sure (since "instance class" isn't really
correct - do you mean "derived class"?), but it's possible you just want to
make Foo() virtual.

///ark
Jul 6 '06 #6
>>I am curious why you have Foo( ) in BaseClass if Update( ) might not
exist to be called?

Update() will always exist.
John, I don't know what the type will be so this code doesn't work:

public void Foo()
{
if (this is Derived)
{
Derived d = (Derived)this;
d.Update();
}
}

I was trying to provide a simple example but the code does this:

public class BaseClass<T>{...}

public class MyClass: BaseClass<Person>, IClass<Person>{...}

I guess I'm not sure how your code would apply in this case.

In the end, how is your technique any better tham what I'm doing? We
are both still casting.

I can't use abstract because the base class has method bodies that do
something. In other words, it isn't an abstract class.
Thanks,
Brett

Jul 6 '06 #7
Brett Romero wrote:
>>>I am curious why you have Foo( ) in BaseClass if Update( ) might not
exist to be called?

Update() will always exist.
John, I don't know what the type will be so this code doesn't work:

public void Foo()
{
if (this is Derived)
{
Derived d = (Derived)this;
d.Update();
}
}

I was trying to provide a simple example but the code does this:

public class BaseClass<T>{...}

public class MyClass: BaseClass<Person>, IClass<Person>{...}

I guess I'm not sure how your code would apply in this case.

In the end, how is your technique any better tham what I'm doing? We
are both still casting.

I can't use abstract because the base class has method bodies that do
something. In other words, it isn't an abstract class.
Thanks,
Brett
Hi Brett,
Update() will always exist.
I know you say that, but the compiler doesn't know that. It is conceivable
that you could create a derived class that does not implement an Update()
method. You need to instruct the compilre that Update() will always exist.

To do this, you define your base class as being abstract, and your Update()
method as abstract:

public abstract class BaseClass
{
public void Foo()
{
Update();
}

public abstract void Update();
}

An abstract class cannot be instantiated, however, and if you require this
functionality, remove the abstract modifiers, and define the Update()
method as virtual, and in your base class, provide no implementation:

public class BaseClass
{
public void Foo()
{
Update();
}

public virtual void Update()
{
}
}

Now, any derived classes from the abstract version MUST override Update():

public class DerivedClass : BaseClass
{
public override void Update()
{
// Implementation
}
}

Or, derived classes from the virtual version MAY override Update():

public class DerivedClass : BaseClass
{
public override void Update()
{
// Implementation
}
}

--
Hope this helps,
Tom Spink
Jul 6 '06 #8

Brett Romero wrote:
I can't use abstract because the base class has method bodies that do
something. In other words, it isn't an abstract class.
You are mistaken as to what an abstract class is.

An abstract class can have methods and properties that do things, just
like a normal class. The only thing that makes it abstract is that
there is _at least one_ method / property / event / etc. that isn't
defined in the class and so must be defined in child classes.

The only reason that you couldn't have BaseClass be abstract is if
there is some situation in which you have to instantiate a base class
instance. If all you ever want is child class instances then BaseClass
can be abstract.

Jul 6 '06 #9
Hi Brett,
I guess I don't understand your question. The way your original sample
was written, it would not compile because Update( ) is not available to
the base class. From your original post,
How can I have the base class know which instance class has inherited
it and use a method in the instance class? Only certain types of
classes will use the base and those classes will always have an
Update() method.
I thought you wanted a way to figure out which subclasses had the
Update( ) method that could be called, and in a way that the code would
compile. And I assumed you didn't want to add Update( ) to the base
class for some reason (although, as others have pointed out, making
this a virtual or abstract member would also solve your problem).

As for the "we're both still casting" question. Well, of course --
there is no way around it. If the Update( ) member does not exist in
the base class, you're going to need a different type to perform the
call. The only difference is that my sample will not attempt to cast
if the derived type doesn't have the Update( ) member (no runtime
error).

Since you say that Update( ) will always exist, I think I agree with
the other comments here that it should be an abstract or virtual method
in the base class.

Best,
John

Brett Romero wrote:
>I am curious why you have Foo( ) in BaseClass if Update( ) might not
exist to be called?

Update() will always exist.
John, I don't know what the type will be so this code doesn't work:

public void Foo()
{
if (this is Derived)
{
Derived d = (Derived)this;
d.Update();
}
}

I was trying to provide a simple example but the code does this:

public class BaseClass<T>{...}

public class MyClass: BaseClass<Person>, IClass<Person>{...}

I guess I'm not sure how your code would apply in this case.

In the end, how is your technique any better tham what I'm doing? We
are both still casting.

I can't use abstract because the base class has method bodies that do
something. In other words, it isn't an abstract class.
Thanks,
Brett
Jul 7 '06 #10
I went with making the class abstract and certain methods in the class
abstract (those that were in the interface). I've completely dropped
the interface and all is working fine. All of the casting has gone
away as well.

Thanks all.
Brett

Jul 7 '06 #11

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

Similar topics

15
by: JustSomeGuy | last post by:
this doesn't want to compile.... class image : public std::list<element> { element getElement(key k) const { image::iterator iter; for (iter=begin(); iter != end(); ++iter) { element...
11
by: Noah Coad [MVP .NET/C#] | last post by:
How do you make a member of a class mandatory to override with a _new_ definition? For example, when inheriting from System.Collections.CollectionBase, you are required to implement certain...
3
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
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...
23
by: René Nordby | last post by:
Hi there, Is there anyone that knows how to do the following? I have a class A and a class B, that 100% inherits from class A (this means that I don't have other code in class B, than...
2
by: Enrique Bustamante | last post by:
Casting arrays that works on watch and command window but not in code. My application is casting arrays in a way it should work. To test if I was doing something invalid, I wrote a test code that...
8
by: Gamma | last post by:
I'm trying to inherit subclass from System.Diagnostics.Process, but whenever I cast a "Process" object to it's subclass, I encounter an exception "System.InvalidCastException" ("Specified cast is...
9
by: Jess | last post by:
Hello, It seems both static_cast and dynamic_cast can cast a base class pointer/reference to a derived class pointer/reference. If so, is there any difference between them? In addition, if I...
4
by: AalaarDB | last post by:
struct base { int x, y, z; base() {x = 0; y = 0; z = 0;}; base(int x1, int y1, int z1) {x = x1; y = y1; z = z1;}; }; struct intermediate1 : public virtual base {}; struct intermediate2 :...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...

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.