473,748 Members | 6,418 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

"dynamic_ca st" with instance of an abstract class ?!?

Hi @all,

I've got an interesting problem.

These are my classes:

----------------------

class fooBase
{
virtual func();
}

class fooA : public fooBase
{
virtual func();
};

class fooB : public fooBase
{
virtual func1() = 0;
virtual func2();
};

class fooB2 : public fooB
{
virtual func1();
}

----------------------

// Template class
class myFooBase
{
fooBase *m_pPtr;
};

template <class T>
class myFoo : public myFooBase
{
public:

myFoo(fooBase *p_pPtr) :
m_pPtr(p_pPtr)
{
}

bool isCompatible(my Foo *p_p)
{
// Check, if p_p is compatible (dynamic_castab le) to T

// Possible way:
T *TempPtr = new T();
if (dynamic_cast<T *> (p_p->m_pPtr))
}
};

----------------------

int main()
{
fooB2 *TEST1 = new fooB2();

myFoo<fooB2> test1(dynamic_c ast<fooBase *>(new fooB2()));
myFoo<fooBase> test2(dynamic_c ast<fooBase *>(new fooBase()));

// Test: OK
test2.isCompati ble(&test1);

// Cannot create, because of new T() => fooB is an abstract class
myFoo<fooB> test3(dynamic_c ast<fooBase *>(new fooB3()))
}

----------------------

As you see, I need another way to check, if to base classes are
dynamically castable or have the same base classes.

Jul 23 '05
19 4067
Alf P. Steinbach wrote:
* Ralph D. Ungermann:
* tt******@gmx.de:
Now I want to know [presumably at compile time], if A is a
derivation of B!


Since std::type_info offers no way to check the hierarchy, and nobody
else provided a good answer yet, I suppose, that this can't be done in
general.

Andrei Alexandrescu presented one solution to this problem in his "Modern
C++ Design". It's based on having a function with one overload that
accepts a B, and one that accepts anything else. Then you pseudo-call it
(within a sizeof-expression) with an A, and check which one is selected.


Well, I was just confused about the talk about a runtime solution. If
both types are known at compile time, and both types are complete,
then you can use Boost.Type_Trai ts.

http://www.boost.org/libs/type_traits/index.html

Look for "is_base_and_de rived". The only problem is, it will detect
if there exists a "base-berived" relationship between the two classes,
and it will report "true" even if the base type is not accessible
(protected/private inheritance) or if the cast is ambiguous (multiple
"base" are reachable from "derived"). In both cases a cast would fail
to compile - or in case of a dynamic cast maybe compile but fail at
runtime.

But there is also a "is_convertible <T,U>" template that will detect if
a "T" is convertible to an "U". To check if an implicit pointer
conversion is possible just feed in the pointer types, i.e.
"boost::is_conv ertible<A*,B*>: :value" will tell in your case.

The boost implementation of "is_convertible " is actually based on
Alexandrescu's design. And it should work right out of the box with
the majority of compilers.
Jul 23 '05 #11
* Paul Groke:
Alf P. Steinbach wrote:
* Ralph D. Ungermann:
* tt******@gmx.de:

Now I want to know [presumably at compile time], if A is a
derivation of B!

Since std::type_info offers no way to check the hierarchy, and nobody
else provided a good answer yet, I suppose, that this can't be done in
general.

Andrei Alexandrescu presented one solution to this problem in his "Modern
C++ Design". It's based on having a function with one overload that
accepts a B, and one that accepts anything else. Then you pseudo-call it
(within a sizeof-expression) with an A, and check which one is selected.


Well, I was just confused about the talk about a runtime solution.


Uhm. If the types are known at all at run-time, then it can be done at
run-time, e.g. a dynamic_cast. If the types are unknown at run-time, i.e.
non-polymorphic objects used polymorphically , then the design is incorrect.

[snipped good references to Boost; the OP might also consider Loki]

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #12
Alf P. Steinbach wrote:
* Paul Groke:
Alf P. Steinbach wrote:
* Ralph D. Ungermann:
* tt******@gmx.de:
>Now I want to know [presumably at compile time], if A is a
>derivati on of B!

Since std::type_info offers no way to check the hierarchy, and nobody
else provided a good answer yet, I suppose, that this can't be done in
general.
Andrei Alexandrescu presented one solution to this problem in his "Modern
C++ Design". It's based on having a function with one overload that
accepts a B, and one that accepts anything else. Then you pseudo-call it
(within a sizeof-expression) with an A, and check which one is selected.


Well, I was just confused about the talk about a runtime solution.

Uhm. If the types are known at all at run-time, then it can be done at
run-time, e.g. a dynamic_cast. If the types are unknown at run-time, i.e.
non-polymorphic objects used polymorphically , then the design is incorrect.

[snipped good references to Boost; the OP might also consider Loki]


Since the "is_convertible " is a problem that can be dealt with at
compile-time I was assuming that maybe the problem was something
different. I have to say I didn't fully understand what exactly the
OP wanted to do until his last posting.
Jul 23 '05 #13
I want to check, if one type is a derivation of another type!
I cannot use dynamic_cast, because I cannot create an instance of one
of these types (abstract).
Why want I do this at run-time? I have to detect errors which I made
when programming...

Jul 23 '05 #14
* tt******@gmx.de:
I want to check, if one type is a derivation of another type!
I cannot use dynamic_cast, because I cannot create an instance of one
of these types (abstract).
Why want I do this at run-time? I have to detect errors which I made
when programming...


AFAICS solutions have been presented for all possible scenarios.

Perhaps if you could post a minimal real example.

Your earlier code snippets were not valid C++, and the explanations
didn't make sense.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #15
Please check this code:
(Now it is a very good example)

--------------------

class c1
{
virtual void foo() = 0;
....
};

class c2 : public c1
{
....
};

class c3 : public c2
{
....
};

class bad1
{
.....
};

--------------------

class Base
{
public:
virtual ~Base() {}
};

template <class T>
class Checker : public Base
{
public:
T* ptr;

bool check(Base &base)
{
---- PSEUDO (with dynamic_cast, which does not work, if
ptr is NULL - a temporary instance cannot be created, because T can
always be a abstract class):
if (Checker *checker = dynamic_cast<Ch ecker *>(&base))
{
if (dynamic_cast<T *> (checker->ptr))
return true;
}
return false;
----
}
};
main()
{
Checker<c1> checker1;
Checker<c2> checker2;
Checker<c3> checker3;
Checker<bad1> checker4;

checker1.check( checker1) // return true
checker1.check( checker2) // return true
checker1.check( checker3) // return true
checker1.check( checker4) // return false, because bad1 cannot be
casted to c1

}
--------------

Do *****NOT***** use dynamic_cast!!! !!!
Do *****NOT***** use dynamic_cast!!! !!!
Do *****NOT***** use dynamic_cast!!! !!!

Please read the following line in my code:
---- PSEUDO (with dynamic_cast, which does not work, if ptr is NULL - a
temporary instance cannot be created, because T can always be a
abstract class)

Jul 23 '05 #16
* tt******@gmx.de:
template <class T>
class Checker : public Base
{
public:
T* ptr;

bool check(Base &base)
{
---- PSEUDO (with dynamic_cast, which does not work, if
ptr is NULL - a temporary instance cannot be created, because T can
always be a abstract class):
if (Checker *checker = dynamic_cast<Ch ecker *>(&base))
{
if (dynamic_cast<T *> (checker->ptr))
This inner 'if' is equivalent to

if( checker->ptr != 0 )

because it casts a T* pointer to the very same type T*.

return true;
}
return false;
----
}
};


--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #17
Of course you are right....
another example

--------------------

class c
{
};

class c1 : public c
{
virtual void foo() = 0;
....
};
class c2 : public c1
{
....
};
class c3 : public c2
{
....
};
class bad1 : public c
{
.....
};
--------------------

class Base
{
public:
c *ptr;

virtual ~Base() {}
};
template <class T>
class Checker : public Base
{
public:
bool check(Base &base)
{
---- PSEUDO (with dynamic_cast, which does not work, if
ptr is NULL - a temporary instance cannot be created, because T can
always be a abstract class):
if (dynamic_cast<T *> (base.ptr))
return true;
return false;
----
}
void setPtr(c *p_ptr)
{
ptr = dynamic_cast<T *> (p_ptr);
}
};

main()
{
Checker<c1> checker1;
Checker<c2> checker2;
Checker<c3> checker3;
Checker<bad1> checker4;

checker1.check( checker1) // return true
checker1.check( checker2) // return true
checker1.check( checker3) // return true
checker1.check( checker4) // return false, because bad1 cannot be
casted to c1
}
--------------

Do *****NOT***** use dynamic_cast!!! !!!
Do *****NOT***** use dynamic_cast!!! !!!
Do *****NOT***** use dynamic_cast!!! !!!
Please read the following line in my code:
---- PSEUDO (with dynamic_cast, which does not work, if ptr is NULL - a

temporary instance cannot be created, because T can always be a
abstract class)

Jul 23 '05 #18
* tt******@gmx.de:
Of course you are right....
another example

--------------------

class c
{
};

class c1 : public c
{
virtual void foo() = 0;
...
};
class c2 : public c1
{
...
};
class c3 : public c2
{
...
};
class bad1 : public c
{
....
};
--------------------

class Base
{
public:
c *ptr;

virtual ~Base() {}
};
template <class T>
class Checker : public Base
{
public:
bool check(Base &base)
{
---- PSEUDO (with dynamic_cast, which does not work, if
ptr is NULL - a temporary instance cannot be created, because T can
always be a abstract class):
if (dynamic_cast<T *> (base.ptr))
return true;
return false;
This shouldn't compile because class 'c' isn't polymorphic.

Tested: it doesn't compile (when typos corrected in the rest of
code) using MSVC 7.1.

If the problem is to _only_ add some code in here that does "the right
thing", then that's impossible because 'c' isn't polymorphic. However,
you can add code elsewhere that retains type information. The easiest
would be to make class 'c' polymorphic by adding a virtual destructor,
and then write, here,

return (dynamic_cast<T *>( base.ptr ) != 0);

I don't understand your comment about the pointer being 0.

If the pointer is zero then it isn't pointing to anything: which result,
if any, would you like in that case?

}
void setPtr(c *p_ptr)
{
ptr = dynamic_cast<T *> (p_ptr);
}
};

main()
{
Checker<c1> checker1;
Checker<c2> checker2;
Checker<c3> checker3;
Checker<bad1> checker4;

checker1.check( checker1) // return true
checker1.check( checker2) // return true
checker1.check( checker3) // return true
checker1.check( checker4) // return false, because bad1 cannot be
casted to c1
}


--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Jul 23 '05 #19
You are right... the pointer does not point to anything! I know that
dynamic_cast does not work here! I know, that it return NULL, which is
the only right value! I know that there is another intention..

The result I need is different and simple: I do not need a pointer!!!!
I need BOOL! Is castable or is not castable! Of course I know, that a
NULL pointer is never castable. But my question: would it be castable
if there will be a value in it!

By the way: My Compiler (BCB 5.0) compiles the code... I only had to
correct syntax errors and implement "virtual ~c() {}" in class c.
Without dynamic_cast would not work!
But I say it again: dynamic_cast is NOT what I need.

Jul 23 '05 #20

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

Similar topics

6
6024
by: Jordi Vilar | last post by:
Hi All, Is there a way to dynamic_cast a pointer to a type defined by a type_info*? something like: type_info *info_of_type_to_cast = typeid(type_to_cast); type_to_cast *casted = really_dynamic_cast<info_of_type_to_cast>(my_data_ptr);
11
2100
by: Joseph Turian | last post by:
Fellow hackers, I have a class BuildNode that inherits from class Node. Similarly, I have a class BuildTree that inherits from class Tree. Tree includes a member variable: vector<Node> nodes; // For clarity, let this be "orig_nodes" BuildTree includes a member variable:
2
2816
by: Torsten Landschoff | last post by:
Hi there, I am having an interesting C++ problem which I currently am working around but I don't like this so perhaps somebody has a better idea. Basically I am parsing (rather: scanning) a specification (Word document, ugh) and want to generate code from the information I gather, mostly argument passing stuff. The types I have to (un)marshal are currently represented by the
53
4593
by: Alf P. Steinbach | last post by:
So, I got the itch to write something more... I apologize for not doing more on the attempted "Correct C++ Tutorial" earlier, but there were reasons. This is an UNFINISHED and RAW document, and at the end there is even pure mindstorming text left in, but already I think it can be very useful. <url: http://home.no.net/dubjai/win32cpptut/special/pointers/preview/pointers_01__alpha.doc.pdf>.
3
1903
by: craig | last post by:
Given two existing but different classes OldA and OldB (that can not be made to derive from any new base class); is there a way to make them both "observer" objects so that they can be put in one central list and updated thru a common interface. (i.e. observer->update( ..))? Potential solution 1 (multiple inheritence): make a small new observer class, and two new classes: NewA: derived from OldA, and Observer,.. and NewB: derived from...
17
2313
by: nicolas.hilaire | last post by:
Hi all, i've read this article http://msdn2.microsoft.com/en-us/library/85af44e9.aspx who first interest me much. I've translated it to use generic instead of template : generic < typename T, typename U > Boolean isinst(U u) {
0
2681
by: mailforpr | last post by:
Hi. Let me introduce an iterator to you, the so-called "Abstract Iterator" I developed the other day. I actually have no idea if there's another "Abstract Iterator" out there, as I have never looked for one on the net (I did browse the boost library though). It doesn't matter right now, anyway. To put it simply, Abstract Iterator is mainly a wrapper class. It helps
18
3642
by: desktop | last post by:
I have 3 types of objects: bob1, bob2 and bob3. Each object is identified by a unique ID which gets returned by the function getId(). All bobs are descendants from class BaseBob which is an abstract class that has the virtual function getId(). I then have a function that prints a special string when a bob meets another bob (all combinations of bobs has to meet and since the are schizophrenic they can also meet themselves):
8
1642
by: Oliver Graeser | last post by:
Hi All, I'm coming from Java to C++ and this is one of the very last problems I have so far... In Java, if I have, say, a class SISNode that extends NetworkNode, I can have a function that returns a NetworkNode but I can assure the compiler that it is in fact a SISNode and therefore call the method getStatus() that only a SISNode has. Like SISnode s,t; NetworkNode n;
0
8987
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
8826
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
9366
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
9316
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,...
1
6793
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
6073
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
4597
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
2777
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2211
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.