473,657 Members | 2,461 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Inheritance question: How to instantiate derived class from base class

This is probably a very introductory object-oriented question, but it
has been nagging me for years, and since I've never been able to find
the right answer, I've had to work around it with non-optimal code.
However, I suspect there must be a proper object-oriented approach to
solving this problem. Perhaps someone might be able to help me out.

Oftentimes I need to convert an object declared as a base type into a
object of one of its derived classes. Here is an example of my non-
optimal code (what I am doing now). Imagine that
both the base class and derive class are much more complicated than
this with dozens of properties.

/********/

class Shape : System.Object
{
public decimal XCoordinate;
public decimal YCoordinate;
}

class Circle : Shape
{
public decimal Circumference;
}

void main ()
{
//declare a new variable of type Shape
Shape MyShape = new Shape();
MyShape.XCoordi nate = 99;
MyShape.YCoordi nate = 99;

//various programming steps
// ...

//I now decide i need MyShape to be of type Circle
Circle MyCircle = new Circle();

//copy all properites of MyShape into MyCircle
MyCircle.XCoord inate = MyShape.XCoordi nate;
MyCircle.YCoord inate = MyShape.YCoordi nate;
MyCircle.Circum ference = 500;
}

/********/

What I need to know is what is the best way to create a new Circle
object which is an exact copy of all properties of MyShape.
Obviously, copying all properties over from one to the other is not
ideal, because if later I add new properties of the Shape class, I
would want its values copied over to MyCircle, without updating the
above code.

When I try to execute a line like:

MyCircle = (Circle)MyShape ;

That obviously does not work, and throws a runtime error: "A first
chance exception of type 'System.Invalid CastException' occurred".
However, I am sure there must be a proper approach to this, other than
manually creating a new instance and copying over each and every
property.

Thank you for your help.

Mar 6 '07 #1
15 7357
I'm assuming that you cannot, for some reason, know in advance that you want
your shape to be a Circle. If that were the case you could declare it as a
Circle in the first place and just treat it as a Shape until you need it to
be a Circle (e.g. in Arrays of type Shape).

With the above assumption, the best solution I know of is to have a
conversion function in Circle:

public Circle ConvertFromShap e(Shape shape)
{
Circle c = new Circle();
c.XCoordinate = shape.XCoordina te;
c.YCoordinate = shape.YCoordina te;
return c;
}

Now, when you need to convert a Shape to a Circle, you can do:

Shape s = new Shape();
....
....
Circle c = c.ConvertFromSh ape(s);
....
....

Or you might make it static, of course. And you can make the code above
even prettier with good use of constructors: but I assume you don't need me
to tell you that.

It's probably no more efficient, but it is a bit prettier.

HTH
Peter
"Anthony Greene" <an************ @hotmail.comwro te in message
news:11******** *************@n 33g2000cwc.goog legroups.com...
This is probably a very introductory object-oriented question, but it
has been nagging me for years, and since I've never been able to find
the right answer, I've had to work around it with non-optimal code.
However, I suspect there must be a proper object-oriented approach to
solving this problem. Perhaps someone might be able to help me out.

Oftentimes I need to convert an object declared as a base type into a
object of one of its derived classes. Here is an example of my non-
optimal code (what I am doing now). Imagine that
both the base class and derive class are much more complicated than
this with dozens of properties.

/********/

class Shape : System.Object
{
public decimal XCoordinate;
public decimal YCoordinate;
}

class Circle : Shape
{
public decimal Circumference;
}

void main ()
{
//declare a new variable of type Shape
Shape MyShape = new Shape();
MyShape.XCoordi nate = 99;
MyShape.YCoordi nate = 99;

//various programming steps
// ...

//I now decide i need MyShape to be of type Circle
Circle MyCircle = new Circle();

//copy all properites of MyShape into MyCircle
MyCircle.XCoord inate = MyShape.XCoordi nate;
MyCircle.YCoord inate = MyShape.YCoordi nate;
MyCircle.Circum ference = 500;
}

/********/

What I need to know is what is the best way to create a new Circle
object which is an exact copy of all properties of MyShape.
Obviously, copying all properties over from one to the other is not
ideal, because if later I add new properties of the Shape class, I
would want its values copied over to MyCircle, without updating the
above code.

When I try to execute a line like:

MyCircle = (Circle)MyShape ;

That obviously does not work, and throws a runtime error: "A first
chance exception of type 'System.Invalid CastException' occurred".
However, I am sure there must be a proper approach to this, other than
manually creating a new instance and copying over each and every
property.

Thank you for your help.

Mar 6 '07 #2
hi Anthony,

Anthony Greene wrote:
What I need to know is what is the best way to create a new Circle
object which is an exact copy of all properties of MyShape.
I would use some kind of "copy" constructor, not tested:

class Shape
{
public void CopyTo(Shape toShape) {}
}

class Circle : Shape
{
public Circle() {};
public Circle(Shape fromShape) { fromShape.CopyT o((Shape)this) };
public decimal Circumference;
}

When changing properties of Shape you just have to change the CopyTo()
method.
mfG
--stefan <--
Mar 6 '07 #3
Anthony Greene wrote:
This is probably a very introductory object-oriented question, but it
has been nagging me for years, and since I've never been able to find
the right answer, I've had to work around it with non-optimal code.
However, I suspect there must be a proper object-oriented approach to
solving this problem. Perhaps someone might be able to help me out.

Oftentimes I need to convert an object declared as a base type into a
object of one of its derived classes. Here is an example of my non-
optimal code (what I am doing now). Imagine that
both the base class and derive class are much more complicated than
this with dozens of properties.

/********/

class Shape : System.Object
{
public decimal XCoordinate;
public decimal YCoordinate;
}

class Circle : Shape
{
public decimal Circumference;
}

void main ()
{
//declare a new variable of type Shape
Shape MyShape = new Shape();
MyShape.XCoordi nate = 99;
MyShape.YCoordi nate = 99;

//various programming steps
// ...

//I now decide i need MyShape to be of type Circle
Circle MyCircle = new Circle();

//copy all properites of MyShape into MyCircle
MyCircle.XCoord inate = MyShape.XCoordi nate;
MyCircle.YCoord inate = MyShape.YCoordi nate;
MyCircle.Circum ference = 500;
}

/********/

What I need to know is what is the best way to create a new Circle
object which is an exact copy of all properties of MyShape.
Obviously, copying all properties over from one to the other is not
ideal, because if later I add new properties of the Shape class, I
would want its values copied over to MyCircle, without updating the
above code.

When I try to execute a line like:

MyCircle = (Circle)MyShape ;

That obviously does not work, and throws a runtime error: "A first
chance exception of type 'System.Invalid CastException' occurred".
However, I am sure there must be a proper approach to this, other than
manually creating a new instance and copying over each and every
property.

Thank you for your help.
You could do it using reflection, but there's a reason this type of stuff
isn't easy, it's usually not a good idea and certainly not nearly as simple
as your Circle/Shape example. If you want to be able to create a Circle
from a Shape, you should be explicit in how that is done, meaning clearly
stating which properties of Shape get copied to Circle and how. You can
make this easier on consumers of Circle by giving Circle a non-default
constructor which takes in an instance of Shape, thus allowing the consumer
to write Circle MyCircle = new Circle(MyShape) ;. But within that
constructor you'll be manually setting the properties of Circle from Shape
as are appropriate. In your simplistic example it may not be clear why it's
not a good idea to have this type of construction be automatic. There are
many real-world examples where automating this type of object construction
would cause problems.

If you are sure you always want the properties from your base Shape copied
directly, you could use a variation on the above. That would be to give
Shape a copy constructor, and have the Circle constructor that takes in a
Shape delegate that to the base Shape object. Ex:

public class Shape
{
public decimal X;
public decimal Y;

public Shape() {}
public Shape(Shape shape)
{
this.X = shape.X;
this.Y = shape.Y;
}
}

public class Circle
{
public decimal C;

public Circle(){}
public Circle(Shape shape) : base (shape) {}
public Circle(Circle circle) : base (circle)
{
this.C = circle.C;
}
}
--
Tom Porterfield

Mar 6 '07 #4
Copy constructor. http://en.wikipedia.org/wiki/Copy_constructor

Like:

class Shape
{
public decimal XCoordinate;
public decimal YCoordinate;

public Shape() { }

protected Shape(Shape copyshape)
{
XCoordinate = copyshape.XCoor dinate;
YCoordinate = copyshape.YCoor dinate;
}
}

class Circle : Shape
{
public decimal Circumference;

public Circle(Shape shape) : base(shape)
{
Circumference = 1.0m;
}
}

static void Main(string[] args)
{
Shape newShape = new Shape();
Circle newCircle = new Circle(newShape );

}

Cicle does not need to know anything about shape. Free to extend as you
like.

"Anthony Greene" <an************ @hotmail.comha scritto nel messaggio
news:11******** *************@n 33g2000cwc.goog legroups.com...
This is probably a very introductory object-oriented question, but it
has been nagging me for years, and since I've never been able to find
the right answer, I've had to work around it with non-optimal code.
However, I suspect there must be a proper object-oriented approach to
solving this problem. Perhaps someone might be able to help me out.

Oftentimes I need to convert an object declared as a base type into a
object of one of its derived classes. Here is an example of my non-
optimal code (what I am doing now). Imagine that
both the base class and derive class are much more complicated than
this with dozens of properties.

/********/

class Shape : System.Object
{
public decimal XCoordinate;
public decimal YCoordinate;
}

class Circle : Shape
{
public decimal Circumference;
}

void main ()
{
//declare a new variable of type Shape
Shape MyShape = new Shape();
MyShape.XCoordi nate = 99;
MyShape.YCoordi nate = 99;

//various programming steps
// ...

//I now decide i need MyShape to be of type Circle
Circle MyCircle = new Circle();

//copy all properites of MyShape into MyCircle
MyCircle.XCoord inate = MyShape.XCoordi nate;
MyCircle.YCoord inate = MyShape.YCoordi nate;
MyCircle.Circum ference = 500;
}

/********/

What I need to know is what is the best way to create a new Circle
object which is an exact copy of all properties of MyShape.
Obviously, copying all properties over from one to the other is not
ideal, because if later I add new properties of the Shape class, I
would want its values copied over to MyCircle, without updating the
above code.

When I try to execute a line like:

MyCircle = (Circle)MyShape ;

That obviously does not work, and throws a runtime error: "A first
chance exception of type 'System.Invalid CastException' occurred".
However, I am sure there must be a proper approach to this, other than
manually creating a new instance and copying over each and every
property.

Thank you for your help.

Mar 6 '07 #5
Laura T. wrote:
class Shape
{
public decimal XCoordinate;
public decimal YCoordinate;

public Shape() { }

protected Shape(Shape copyshape)
{
XCoordinate = copyshape.XCoor dinate;
YCoordinate = copyshape.YCoor dinate;
}
}

class Circle : Shape
{
public decimal Circumference;

public Circle(Shape shape) : base(shape)
{
Circumference = 1.0m;
}
}

Cicle does not need to know anything about shape. Free to extend as you
like.
Interesting comment that Circle does not need to know anything about shape
in light of the fact that Circle is a Shape and therefore knows a lot about
Shape.
--
Tom Porterfield

Mar 6 '07 #6
On Mar 6, 10:50 am, "Anthony Greene" <anthony.gre... @hotmail.com>
wrote:
This is probably a very introductory object-oriented question, but it
has been nagging me for years, and since I've never been able to find
the right answer, I've had to work around it with non-optimal code.
However, I suspect there must be a proper object-oriented approach to
solving this problem. Perhaps someone might be able to help me out.

Oftentimes I need to convert an object declared as a base type into a
object of one of its derived classes. Here is an example of my non-
optimal code (what I am doing now). Imagine that
both the base class and derive class are much more complicated than
this with dozens of properties.

/********/

class Shape : System.Object
{
public decimal XCoordinate;
public decimal YCoordinate;

}

class Circle : Shape
{
public decimal Circumference;

}

void main ()
{
//declare a new variable of type Shape
Shape MyShape = new Shape();
MyShape.XCoordi nate = 99;
MyShape.YCoordi nate = 99;

//various programming steps
// ...

//I now decide i need MyShape to be of type Circle
Circle MyCircle = new Circle();

//copy all properites of MyShape into MyCircle
MyCircle.XCoord inate = MyShape.XCoordi nate;
MyCircle.YCoord inate = MyShape.YCoordi nate;
MyCircle.Circum ference = 500;

}

/********/

What I need to know is what is the best way to create a new Circle
object which is an exact copy of all properties of MyShape.
Obviously, copying all properties over from one to the other is not
ideal, because if later I add new properties of the Shape class, I
would want its values copied over to MyCircle, without updating the
above code.

When I try to execute a line like:

MyCircle = (Circle)MyShape ;

That obviously does not work, and throws a runtime error: "A first
chance exception of type 'System.Invalid CastException' occurred".
However, I am sure there must be a proper approach to this, other than
manually creating a new instance and copying over each and every
property.

Thank you for your help.
Hi,

I'm thinking of three possibilities.

1) Define a static factory method on Circle called Transorm. That
method would have the logic required to transform any Shape into a
Circle. The Circle contains the logic in this case.

2) Define a virtual instance method on Shape called ToCircle. That
method would have the logic required to transform that particular
Shape into a Circle. Each individual Shape contains the logic in this
case.

3) If there are a lot of shapes in the inheritance hierarchy and you
want to be able to do different kinds of transormations then you may
want to abstract this logic into a separate class or class hierarchy.

Brian

Mar 6 '07 #7
Thank you for your quick and helpful answers.

This is exactly how it's been explained to me previously, and most
times how I have implemented the solution (either using a factory
pattern, or more often, a constructor)

public Circle (Shape baseShape)
{
//etc.
}

For the concerns I outlined above, I was never 100% happy with this
implementation, and thought it there might be a simple object-oriented
construct I was missing that would let me cast the base class as the
derived class. I see now that it's not possible.

I would much prefer not getting into using Reflection for a problem
like this, because I don't believe that 90% of the cases that the
overhead of using Reflection would be worth writing out the code
manually.

Thank you again.

Mar 6 '07 #8
PS

"Anthony Greene" <an************ @hotmail.comwro te in message
news:11******** *************@n 33g2000cwc.goog legroups.com...
This is probably a very introductory object-oriented question, but it
has been nagging me for years, and since I've never been able to find
the right answer, I've had to work around it with non-optimal code.
However, I suspect there must be a proper object-oriented approach to
solving this problem. Perhaps someone might be able to help me out.

Oftentimes I need to convert an object declared as a base type into a
object of one of its derived classes. Here is an example of my non-
optimal code (what I am doing now). Imagine that
both the base class and derive class are much more complicated than
this with dozens of properties.

/********/

class Shape : System.Object
{
public decimal XCoordinate;
public decimal YCoordinate;
}

class Circle : Shape
{
public decimal Circumference;
}

void main ()
{
//declare a new variable of type Shape
Shape MyShape = new Shape();
MyShape.XCoordi nate = 99;
MyShape.YCoordi nate = 99;

//various programming steps
// ...

//I now decide i need MyShape to be of type Circle
Circle MyCircle = new Circle();

//copy all properites of MyShape into MyCircle
MyCircle.XCoord inate = MyShape.XCoordi nate;
MyCircle.YCoord inate = MyShape.YCoordi nate;
MyCircle.Circum ference = 500;
}

/********/

What I need to know is what is the best way to create a new Circle
object which is an exact copy of all properties of MyShape.
Obviously, copying all properties over from one to the other is not
ideal, because if later I add new properties of the Shape class, I
would want its values copied over to MyCircle, without updating the
above code.

When I try to execute a line like:

MyCircle = (Circle)MyShape ;

That obviously does not work, and throws a runtime error: "A first
chance exception of type 'System.Invalid CastException' occurred".
However, I am sure there must be a proper approach to this, other than
manually creating a new instance and copying over each and every
property.
see http://en.wikipedia.org/wiki/Prototype_pattern
Mar 6 '07 #9
PS wrote:
"Anthony Greene" <an************ @hotmail.comwro te in message
news:11******** *************@n 33g2000cwc.goog legroups.com...
>This is probably a very introductory object-oriented question, but it
has been nagging me for years, and since I've never been able to find
the right answer, I've had to work around it with non-optimal code.
However, I suspect there must be a proper object-oriented approach to
solving this problem. Perhaps someone might be able to help me out.

Oftentimes I need to convert an object declared as a base type into a
object of one of its derived classes. Here is an example of my non-
optimal code (what I am doing now). Imagine that
both the base class and derive class are much more complicated than
this with dozens of properties.
see http://en.wikipedia.org/wiki/Prototype_pattern
The prototype pattern doesn't solve this problem. He wants to be able to
create a derived object based on an instance of a base object. Prototype is
used to create the same type of object from an existing instance of the same
type of object, not from a base or derived object. Typically you'll see
prototype used when instantiation of a new object is more expensive than
copying an existing object, or in conjunction with a factory pattern when
you want to abstract away from the client the complexity of knowing exactly
what type of object to create.
--
Tom Porterfield

Mar 6 '07 #10

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

Similar topics

4
1639
by: Peter Hamilton | last post by:
I am trying to implement inheritance but I am having a difficult time with some concepts. What I am trying to do is have a Child object inherit from the Parent, and when you set a property value at the Parent level, I want all of the children to see this change. Likewise, when I set a Parent's property value in the child object, both the parent and all of the children see the change. Maybe what I am trying to do is not "inheritance" after...
8
3214
by: Shawn Casey | last post by:
Consider the following code: interface IBase { virtual void BaseFunction() = 0; }; interface IDerived : public IBase { virtual void DerivedFunction() = 0;
45
6338
by: Ben Blank | last post by:
I'm writing a family of classes which all inherit most of their methods and code (including constructors) from a single base class. When attempting to instance one of the derived classes using parameters, I get CS1501 (no method with X arguments). Here's a simplified example which mimics the circumstances: namespace InheritError { // Random base class. public class A { protected int i;
6
1652
by: JD | last post by:
Hi I had 2 forms inheriting from a base one. It all worked nicely to start off with. Don't know what I did next (did some code in the base form), because now the VS IDE doesn't want to open either of the child forms. It complains about "ConnectionString property has not been initialized". I'm tryig to build a 3 tier application so there is no DB connections on mypresentation layer. But then, I just started C# so am probably missing...
1
1773
by: relient | last post by:
Hi, I just started the chapter on "Inheritance" and I'm a bit confused so I have three questions: first, here's the code: using System; using System.Collections.Generic; using System.Text; namespace ConsoleProject1 { public class Base
5
1314
by: relient | last post by:
This is rediculous. It is said when you override a method in a derived class that's implemented in the base class, you "override the base class methods" implementation, correct? but in my test, base.SomeMethod() still prints out it's *own* implimentation - that's tottally different from the deriveds overrided method. I don't get it. Really, What's the difference betwen this.SomeMethod() and base.SomeMethod()? more precisely, is *this* and...
2
1854
by: Heinz Ketchup | last post by:
Hello, I'm looking to bounce ideas off of anyone, since mainly the idea of using Multiple Virtual Inheritance seems rather nutty. I chalk it up to my lack of C++ Experience. Here is my scenario... I have 5 Derived Classes I have 3 Base Classes
12
2360
by: Massimo | last post by:
Hi to all, I'm facing a problem in a particularly complex inheritance hierarchy, and I'd like to know what the standard says about it and if my compiler is correct in what it does. I have two consecutive layers of diamond-shaped inheritance; the first layer is declared as using virtual inheritance, while the second one is declared as *not* using it. This is what I'd like to have:
3
2548
by: Jess | last post by:
Hello, I've been reading Effective C++ about multiple inheritance, but I still have a few questions. Can someone give me some help please? First, it is said that if virtual inheritance is used, then "the responsibility for initializing a virtual base is borne by the most derived class in the hierarchy". What does it mean? Initializing base class is usually done automatically by the compiler, but a derived class can invoke the base...
0
8392
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
8305
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,...
1
8503
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
8603
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
7320
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
5632
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
4151
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...
1
2726
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
1944
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.