473,806 Members | 2,346 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Cast to derived class?

Hi all,

lately I had a problem where I wanted to cast a basic class to a
derived type, which did not introduce any new members and did not
change any stuff with dynamically allocated memory. I just wanted to
add some methods to the class.

So my question is:
Is it valid C++ to create a basic class and to cast it to a derived
one the way I did in my example below? The example works fine for
MinGW, but I'm not sure if this is ABI dependent.

Example code:

<code>

#include <stdio.h>

class Basic {

public:
Basic(int a, int b) {
a_ = a;
b_ = b;
};

int getA() {
return a_;
};
int getB() {
return b_;
};

private:
int a_, b_;
};

class Derived : Basic {

public:
Derived(int a, int b) : Basic(a, b) {}
;

int multiply() {
return getA() * getB();
};
};
int main() {
Basic *basic = new Basic(2, 4);

Derived *derived = (Derived *)basic;
printf("%d * %d = %d\n", basic->getA(), basic->getB(), derived-
>multiply());
delete basic;

return 0;
}

</code>

Nov 12 '07 #1
5 2490
ch************* ******@googlema il.com wrote:
Hi all,

So my question is:
Is it valid C++ to create a basic class and to cast it to a derived
one the way I did in my example below? The example works fine for
MinGW, but I'm not sure if this is ABI dependent.

Example code:
<snip/>
>
int main() {
Basic *basic = new Basic(2, 4);

Derived *derived = (Derived *)basic;
The fact you had to resort to a C style cast is a strong indicator that
this is a bad idea.

The only safe way to cast from a Basic* is to use dynamic_cast and for
that to work, the Basic* must point to a Derived.

--
Ian Collins.
Nov 12 '07 #2
I see I have to be a bit more specific about my problem:

I was trying to write a simulation model for some quite primitive IC
similar to a USB flash chip.

To abstract the memory I wrote some class which clusters the memory
into blocks and enables for write and read access.

Now my IC allows for 2 completely different approaches to justify
access rights on that very same memory (I know this sounds like a bad
idea, but its not up to me to change that).

So I wanted to have 2 derived classes, which will do the checking for
access conditions. But I do not want to use 2 instances of the memory
as I would need to keep them synchronized.

So I have the following model:

-----------
base memory
-----------
/ \
--------- ---------
derived 1 derived 2
--------- ---------

Where derived 1/2 simply read parts of the memory (through a base
method) and return true/false for some access condition checks.

What I wanted to do is instantiate some "derived 1 memory" and cast it
for some other AC checks to "derived 2"
As far as I can see from your answers I should create a new class
which derives from "derived 1" and "derived 2" instead of my casting
approach.
thanks for your replies!
--
Christian Pontesegger

Nov 12 '07 #3
On Nov 12, 10:42 am, christian.ponte seg...@googlema il.com wrote:
I see I have to be a bit more specific about my problem:

I was trying to write a simulation model for some quite primitive IC
similar to a USB flash chip.

To abstract the memory I wrote some class which clusters the memory
into blocks and enables for write and read access.

Now my IC allows for 2 completely different approaches to justify
access rights on that very same memory (I know this sounds like a bad
idea, but its not up to me to change that).

So I wanted to have 2 derived classes, which will do the checking for
access conditions. But I do not want to use 2 instances of the memory
as I would need to keep them synchronized.

So I have the following model:

-----------
base memory
-----------
/ \
--------- ---------
derived 1 derived 2
--------- ---------

Where derived 1/2 simply read parts of the memory (through a base
method) and return true/false for some access condition checks.

What I wanted to do is instantiate some "derived 1 memory" and cast it
for some other AC checks to "derived 2"

As far as I can see from your answers I should create a new class
which derives from "derived 1" and "derived 2" instead of my casting
approach.

thanks for your replies!
--
Christian Pontesegger
I would create one class that represents the memory, one class that
allows you to access to the memory and derive the two classes from
that one.
This would allow you to access to the same memory object from two or
more different "access" objects.

Paolo Brandoli

Nov 12 '07 #4
On 2007-11-12 03:01:55 -0500, Ian Collins <ia******@hotma il.comsaid:
ch************* ******@googlema il.com wrote:
>Hi all,

So my question is:
Is it valid C++ to create a basic class and to cast it to a derived
one the way I did in my example below? The example works fine for
MinGW, but I'm not sure if this is ABI dependent.

Example code:
<snip/>
>>
int main() {
Basic *basic = new Basic(2, 4);

Derived *derived = (Derived *)basic;

The fact you had to resort to a C style cast is a strong indicator that
this is a bad idea.
A static_cast would have worked, too.
>
The only safe way to cast from a Basic* is to use dynamic_cast and for
that to work, the Basic* must point to a Derived.
For a rather restrictive meaning of "safe". If you know that the type
object is Derived (not the case here), and Basic* is not pointing to a
virtual base, static_cast works just fine, and is significantly faster.

--
Pete
Roundhouse Consulting, Ltd. (www.versatilecoding.com) Author of "The
Standard C++ Library Extensions: a Tutorial and Reference
(www.petebecker.com/tr1book)

Nov 12 '07 #5
Pete Becker wrote:
On 2007-11-12 03:01:55 -0500, Ian Collins <ia******@hotma il.comsaid:
>ch************* ******@googlema il.com wrote:
>>Hi all,

So my question is:
Is it valid C++ to create a basic class and to cast it to a derived
one the way I did in my example below? The example works fine for
MinGW, but I'm not sure if this is ABI dependent.

Example code:
<snip/>
>>>
int main() {
Basic *basic = new Basic(2, 4);

Derived *derived = (Derived *)basic;

The fact you had to resort to a C style cast is a strong indicator that
this is a bad idea.

A static_cast would have worked, too.
>>
The only safe way to cast from a Basic* is to use dynamic_cast and for
that to work, the Basic* must point to a Derived.

For a rather restrictive meaning of "safe". If you know that the type
object is Derived (not the case here), and Basic* is not pointing to a
virtual base, static_cast works just fine, and is significantly faster.
I was referring to the general case, when the conditions above are not
true, a dynamic_cast will fail where a static_cast will give UB.

--
Ian Collins.
Nov 12 '07 #6

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

Similar topics

3
6579
by: tirath | last post by:
Hi all, I have a templated class that derives from a non-templated abstract class. How do I then cast a base class pointer to a <templated> derived class pointer in a generalised fashion? Here's what I'm generally trying to achieve: I'm building (trying to anyway) a serialization library. Here's my design:
11
2054
by: Alberto Giménez | last post by:
Hi, I've seen some object oriented programming bits out there and i'm not sure if they're legal. For example: struct Object { int field1; int field2; }; struct SubObject { int field1; /* the same as Object */
5
3447
by: Nick Flandry | last post by:
I'm running into an Invalid Cast Exception on an ASP.NET application that runs fine in my development environment (Win2K server running IIS 5) and a test environment (also Win2K server running IIS 5), but fails on IIS 6 running on a Win2003 server. The web uses Pages derived from a custom class I wrote (which itself derives from Page) to provide some common functionality. The Page_Load handler the failing webpage starts out like this: ...
4
3842
by: Mike Cooper | last post by:
There is something about inherited classes I evidently don't know... I wrote the following class: Class Class1 inherits System.Windows.Forms.DataGridTextBoxColumn End Class There is absolutely no added functionality to it.
15
26305
by: mr.peteryu | last post by:
Hi, Can someone explain the idea behind casting to an interface? For example: -> I have an IInterface that contains a Read() method. -> I have an object "obj" that implements IInterface. Why would someone do the following and what does it mean?
6
1414
by: Ron M. Newman | last post by:
Hi, Under what circumstances can I ever get an exception about not being able to cast type "ABC" to type "ABC" if there's only one ABC class in the system and it's loaded from a dynamic assembly? Thanks Ron
11
1793
by: Dinsdale | last post by:
I am trying to determine what the current cast of an object is. Essentially, if I use GetType, it always returns the original type of the object created but I want to know what the current cast of the object is (i.e.: is it still cast as a Derived class, or is it cast as a Base class?) Here is some pseudo code to show the example. Class Base .... End Class
7
3818
by: WaterWalk | last post by:
Hello. I thought I understood member function pointers, but in fact I don't. Consider the following example: class Base { public: virtual ~Base() {} }; class Derived : public Base {
2
252
by: christian.pontesegger | last post by:
Hi all, lately I had a problem where I wanted to cast a basic class to a derived type, which did not introduce any new members and did not change any stuff with dynamically allocated memory. I just wanted to add some methods to the class. So my question is: Is it valid C++ to create a basic class and to cast it to a derived one the way I did in my example below? The example works fine for
0
10618
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
10110
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
9187
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
7649
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
6877
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
5546
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...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4329
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
3008
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.