473,668 Members | 2,600 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Creating a derived object from a base object

Is there an easy/special way to turn a base object into a derived
object? So for example, given the following:

class MyString : String
{
....

}
(ok, so String is sealed, but just play along)

MyString myString = new MyString();
say i want to convert myString to upper case - sure would be nice to
use the ToUpper method of the base String object - but doesn't seem
like i can:

myString.ToUppe r() returns a String, not a MyString

So how can i use ToUpper() if i need the result to be a MyString? I
can't cast the result to a MyString since I can't cast a base type to a

derived type. Are all the String methods that return a new String
instance useless now?

I guess, even more simply, my question is what is the easiest way to
convert a base type to a derived type? How do i convert a String to a
MyString? Given that MyString is a String type, is there any special
way to convert String into MyString? Or is it literally 2 completely
different objects now, just like a String and a Foo Object. And i need
to write a explicit cast method to do the conversion?

Thanks

Dec 5 '06 #1
10 2520
You can never change the type of an object once created. You can however
provide implicit or explicit cast operators that convert between the two
types, and you can provide "new" implementations of methods to change the
return types, but this should be used with caution as any callers using a
subclass object thru a baseclass reference will use the *old* methods.

The following shows a way to use "virtual" and "new" methods to get around
this; called on a baseclass instance always returns a baseclass; called on a
subclass instance always returns a subclass - however note that it is typed
by the reference - so if the caller is referencing it as "BaseClass" it will
see a baseclass, and it if is referencing it as a "SubClass" it will see a
subclass. Either way the instance is still a SubClass. The cast in the "new"
method allows further subclasses to continue to override InnerSomething.

Marc

public class BaseClass {
public BaseClass Something() {
return InnerSomething( );
}

protected virtual BaseClass InnerSomething( ) {
return new BaseClass();
}
}

public class SubClass : BaseClass {
protected override BaseClass InnerSomething( ) {
return new SubClass();
}

public new SubClass Something() {
return (SubClass) InnerSomething( );
}
}
Dec 5 '06 #2
One solution that occurs is to do this, assuming you have a constructor that
takes a string, which seems reasonable:

MyString mystring = new MyString("a lower case string");
mystring = new MyString(mystri ng.ToUpper());

HTH
Peter
"benliu" <be****@iasport smedia.comwrote in message
news:11******** **************@ j44g2000cwa.goo glegroups.com.. .
Is there an easy/special way to turn a base object into a derived
object? So for example, given the following:

class MyString : String
{
...

}
(ok, so String is sealed, but just play along)

MyString myString = new MyString();
say i want to convert myString to upper case - sure would be nice to
use the ToUpper method of the base String object - but doesn't seem
like i can:

myString.ToUppe r() returns a String, not a MyString

So how can i use ToUpper() if i need the result to be a MyString? I
can't cast the result to a MyString since I can't cast a base type to a

derived type. Are all the String methods that return a new String
instance useless now?

I guess, even more simply, my question is what is the easiest way to
convert a base type to a derived type? How do i convert a String to a
MyString? Given that MyString is a String type, is there any special
way to convert String into MyString? Or is it literally 2 completely
different objects now, just like a String and a Foo Object. And i need
to write a explicit cast method to do the conversion?

Thanks

Dec 5 '06 #3
Ok, so your suggested solution is the real issue i'm getting at.

How WOULD you write a MyString constructor that takes a string? You
don't have access to the underlying implementation of String (and even
if you can think of a hacky way, this is just an example, and let's
assume that the String class is a black box). So therefore how would
the constructor create itself from an instance of a String?

So is this now different than in a case that you're trying to create an
object from a completely unrelated object? Seems that since MyString
does not add any new properties to String, there should be a quick easy
way to construct a MyString object from a String object. Maybe not?
Peter Bradley wrote:
One solution that occurs is to do this, assuming you have a constructor that
takes a string, which seems reasonable:

MyString mystring = new MyString("a lower case string");
mystring = new MyString(mystri ng.ToUpper());

HTH
Peter
"benliu" <be****@iasport smedia.comwrote in message
news:11******** **************@ j44g2000cwa.goo glegroups.com.. .
Is there an easy/special way to turn a base object into a derived
object? So for example, given the following:

class MyString : String
{
...

}
(ok, so String is sealed, but just play along)

MyString myString = new MyString();
say i want to convert myString to upper case - sure would be nice to
use the ToUpper method of the base String object - but doesn't seem
like i can:

myString.ToUppe r() returns a String, not a MyString

So how can i use ToUpper() if i need the result to be a MyString? I
can't cast the result to a MyString since I can't cast a base type to a

derived type. Are all the String methods that return a new String
instance useless now?

I guess, even more simply, my question is what is the easiest way to
convert a base type to a derived type? How do i convert a String to a
MyString? Given that MyString is a String type, is there any special
way to convert String into MyString? Or is it literally 2 completely
different objects now, just like a String and a Foo Object. And i need
to write a explicit cast method to do the conversion?

Thanks
Dec 5 '06 #4
Let me further clarify - suppose I want to convert my MyString to
uppercase. String class is a blackbox - i cannot modify it whatsoever.
I don't want to write a separate MyString ToUpper method when String
already implements it. However, String.ToUpper returns a String, not a
MyString. And similarly, even if i was to write my own
MyString.ToUppe r implementation, how would i do it? I don't have
access to the implementations details of String (using String-MyString
as an example - in my real world case, i don't have access to the
implementatino of the base class, so hacking around this using some
special String method will not help)

Thanks!

Marc Gravell wrote:
You can never change the type of an object once created. You can however
provide implicit or explicit cast operators that convert between the two
types, and you can provide "new" implementations of methods to change the
return types, but this should be used with caution as any callers using a
subclass object thru a baseclass reference will use the *old* methods.

The following shows a way to use "virtual" and "new" methods to get around
this; called on a baseclass instance always returns a baseclass; called on a
subclass instance always returns a subclass - however note that it is typed
by the reference - so if the caller is referencing it as "BaseClass" it will
see a baseclass, and it if is referencing it as a "SubClass" it will see a
subclass. Either way the instance is still a SubClass. The cast in the "new"
method allows further subclasses to continue to override InnerSomething.

Marc

public class BaseClass {
public BaseClass Something() {
return InnerSomething( );
}

protected virtual BaseClass InnerSomething( ) {
return new BaseClass();
}
}

public class SubClass : BaseClass {
protected override BaseClass InnerSomething( ) {
return new SubClass();
}

public new SubClass Something() {
return (SubClass) InnerSomething( );
}
}
Dec 5 '06 #5
"benliu" <be****@iasport smedia.comwrote in message
news:11******** **************@ n67g2000cwd.goo glegroups.com.. .
Let me further clarify - suppose I want to convert my MyString to
uppercase. String class is a blackbox - i cannot modify it whatsoever.
I don't want to write a separate MyString ToUpper method when String
already implements it. However, String.ToUpper returns a String, not a
MyString. And similarly, even if i was to write my own
MyString.ToUppe r implementation, how would i do it? I don't have
access to the implementations details of String (using String-MyString
as an example - in my real world case, i don't have access to the
implementatino of the base class, so hacking around this using some
special String method will not help)
Would a class that wrapped String instead of deriving from it help?
Dec 5 '06 #6
Yes, i was thinking about that.

It seems then that i am not crazy - there is no simple way to create a
derived object out of a base object - whether through casting or
creation of new object... Is that the consensus?

Mark Wilden wrote:
"benliu" <be****@iasport smedia.comwrote in message
news:11******** **************@ n67g2000cwd.goo glegroups.com.. .
Let me further clarify - suppose I want to convert my MyString to
uppercase. String class is a blackbox - i cannot modify it whatsoever.
I don't want to write a separate MyString ToUpper method when String
already implements it. However, String.ToUpper returns a String, not a
MyString. And similarly, even if i was to write my own
MyString.ToUppe r implementation, how would i do it? I don't have
access to the implementations details of String (using String-MyString
as an example - in my real world case, i don't have access to the
implementatino of the base class, so hacking around this using some
special String method will not help)

Would a class that wrapped String instead of deriving from it help?
Dec 5 '06 #7
benliu <be****@iasport smedia.comwrote :
Ok, so your suggested solution is the real issue i'm getting at.

How WOULD you write a MyString constructor that takes a string? You
don't have access to the underlying implementation of String (and even
if you can think of a hacky way, this is just an example, and let's
assume that the String class is a black box). So therefore how would
the constructor create itself from an instance of a String?

So is this now different than in a case that you're trying to create an
object from a completely unrelated object? Seems that since MyString
does not add any new properties to String, there should be a quick easy
way to construct a MyString object from a String object. Maybe not?
As you're not adding any data to string, you should just write a class
with static methods which can be called with instances of strings. In
C# 3.0 this will be made more elegant (arguably) with extension
methods.

--
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
Dec 5 '06 #8
By passing the string parameter to the parent constructor.
Peter

"benliu" <be****@iasport smedia.comwrote in message
news:11******** *************@7 9g2000cws.googl egroups.com...
Ok, so your suggested solution is the real issue i'm getting at.

How WOULD you write a MyString constructor that takes a string? You
don't have access to the underlying implementation of String (and even
if you can think of a hacky way, this is just an example, and let's
assume that the String class is a black box). So therefore how would
the constructor create itself from an instance of a String?

So is this now different than in a case that you're trying to create an
object from a completely unrelated object? Seems that since MyString
does not add any new properties to String, there should be a quick easy
way to construct a MyString object from a String object. Maybe not?
Peter Bradley wrote:
>One solution that occurs is to do this, assuming you have a constructor
that
takes a string, which seems reasonable:

MyString mystring = new MyString("a lower case string");
mystring = new MyString(mystri ng.ToUpper());

HTH
Peter
"benliu" <be****@iasport smedia.comwrote in message
news:11******* *************** @j44g2000cwa.go oglegroups.com. ..
Is there an easy/special way to turn a base object into a derived
object? So for example, given the following:

class MyString : String
{
...

}
(ok, so String is sealed, but just play along)

MyString myString = new MyString();
say i want to convert myString to upper case - sure would be nice to
use the ToUpper method of the base String object - but doesn't seem
like i can:

myString.ToUppe r() returns a String, not a MyString

So how can i use ToUpper() if i need the result to be a MyString? I
can't cast the result to a MyString since I can't cast a base type to a

derived type. Are all the String methods that return a new String
instance useless now?

I guess, even more simply, my question is what is the easiest way to
convert a base type to a derived type? How do i convert a String to a
MyString? Given that MyString is a String type, is there any special
way to convert String into MyString? Or is it literally 2 completely
different objects now, just like a String and a Foo Object. And i need
to write a explicit cast method to do the conversion?

Thanks

Dec 6 '06 #9
Ah! I think I get what you're on about.

I thought you were ignoring, for the purposes of this discussion, the fact
that you couldn't inherit from the string class - but now I see that you're
not.

In the case where you can't inherit from the parent, then you'll just have
to provide a wrapper and delegate to the wrapped uninheritable class.
Someone's already suggested this, I think.

Cheers
Peter
"benliu" <be****@iasport smedia.comwrote in message
news:11******** *************@7 9g2000cws.googl egroups.com...
Ok, so your suggested solution is the real issue i'm getting at.

How WOULD you write a MyString constructor that takes a string? You
don't have access to the underlying implementation of String (and even
if you can think of a hacky way, this is just an example, and let's
assume that the String class is a black box). So therefore how would
the constructor create itself from an instance of a String?

So is this now different than in a case that you're trying to create an
object from a completely unrelated object? Seems that since MyString
does not add any new properties to String, there should be a quick easy
way to construct a MyString object from a String object. Maybe not?
Peter Bradley wrote:
>One solution that occurs is to do this, assuming you have a constructor
that
takes a string, which seems reasonable:

MyString mystring = new MyString("a lower case string");
mystring = new MyString(mystri ng.ToUpper());

HTH
Peter
"benliu" <be****@iasport smedia.comwrote in message
news:11******* *************** @j44g2000cwa.go oglegroups.com. ..
Is there an easy/special way to turn a base object into a derived
object? So for example, given the following:

class MyString : String
{
...

}
(ok, so String is sealed, but just play along)

MyString myString = new MyString();
say i want to convert myString to upper case - sure would be nice to
use the ToUpper method of the base String object - but doesn't seem
like i can:

myString.ToUppe r() returns a String, not a MyString

So how can i use ToUpper() if i need the result to be a MyString? I
can't cast the result to a MyString since I can't cast a base type to a

derived type. Are all the String methods that return a new String
instance useless now?

I guess, even more simply, my question is what is the easiest way to
convert a base type to a derived type? How do i convert a String to a
MyString? Given that MyString is a String type, is there any special
way to convert String into MyString? Or is it literally 2 completely
different objects now, just like a String and a Foo Object. And i need
to write a explicit cast method to do the conversion?

Thanks

Dec 6 '06 #10

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

Similar topics

9
4794
by: justanotherguy63 | last post by:
Hi, I am designing an application where to preserve the hierachy and for code substitability, I need to pass an array of derived class object in place of an array of base class object. Since I am using vector class(STL), the compiler does not allow me to do this. I do realize there is a pitfall in this approach(size of arrays not matching etc), but I wonder how to get around this problem. I have a class hierachy with abstract base...
9
1795
by: Larry Woods | last post by:
I have a method in my base class that I want ALL derived classes to use. But, I find that I can create a "Shadow" method in my derived class that "overrides" the method in my base class. Can't figure out what attribute to put on the base class method to prevent this. TIA, Larry Woods
4
5241
by: Jeff | last post by:
The derived class below passes a reference to an object in its own class to its base calss constructor. The code compiles and will run successfully as long as the base class constructor does not attempt to access the object -- since m_object is not actually created and initizialized until after the base constructor has been called. Any thoughts on the practice below? class Base { public:
5
1953
by: Michael | last post by:
Hi, Could you tell me whether the following two statement are the same? Derived class is derived from Base class. 1. Base* ptr1; 2. Derived * ptr2; Does it mean ptr1 is the same as ptr2?
2
2635
by: Jessica | last post by:
I have a base class and a derived class, but I am getting errors when I try to access functions of the derived class. Simplified version of my code is as follows: //////////////// // test2.hh class BaseClass {
26
5356
by: nyathancha | last post by:
Hi, How Do I create an instance of a derived class from an instance of a base class, essentially wrapping up an existing base class with some additional functionality. The reason I need this is because I am not always able to control/create all the different constructors the base class has. My problem can be described in code as follows ... /* This is the base class with a whole heap of constructors/functionality*/ public class Animal
10
3591
by: Dom Jackson | last post by:
I have a program which crashes when: 1 - I use static_cast to turn a base type pointer into a pointer to a derived type 2 - I use this new pointer to call a function in an object of the derived type 3 - this function then 'grows' the derived type object (by pushing onto a vector).
1
1972
by: Charles Law | last post by:
I have a base class MyBaseClass, and several classes that inherit from it: MyClass1, MyClass2, etc. The base class implements IEnumerable(Of IMyBaseClassRow). The base class has a DataTable object that contains different data depending on which of MyClass1, MyClass2 are instantiated. I want to be able to iterate through the rows of the data table using For Each on my derived classes retrieving a custom row with properties specific to...
10
4085
by: blangela | last post by:
If I pass a base class object by reference (likely does not make a difference here that it is passed by reference) as a parameter to a derived class member function, the member function is not allowed to access the protected data members of the base object. This surprises me. Can someone explain why this is? I suspect there is a good reason and I am just having a slow day to not come up with it myself. Bob
0
8371
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
8889
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
8790
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
8572
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
8652
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...
1
6206
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...
0
4372
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2782
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
2
2017
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.