473,581 Members | 2,783 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

virtual & casting

classes that have virtual methods hold pointer to virtual table as
additional implicit data member. So, sizeof of such classes is sizeof
of all data (as struct-POD) plus 4.
It seems that use of casting for such classes is quite dangerous.
See sample below.

Why does reinterpret_cas t permit such a casting?

=============== ======
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for
80x86

====== foo.cpp ======
#include <iostream>
using namespace std;

#define BUF_SIZE 8
#define SHOW(x) cout << #x << " = " << x << endl

struct Foo1
{
void foo() {} // non-virtual
char m_buf[BUF_SIZE];
void display(int in_start = 0)
{
cout << "Foo1 [" << in_start << ", " << (sizeof (m_buf) - 1) << "]
= ";
for (int i = in_start; i < static_cast<int >(sizeof (m_buf)); i++)
{
cout << m_buf[i];
}
cout << endl;
}

};

struct Foo2
{
virtual void foo() {} // virtual
char m_buf[BUF_SIZE];
void display(int in_start = 0)
{
cout << "Foo2 [" << in_start << ", " << (sizeof (m_buf) - 1) << "]
= ";
for (int i = in_start; i < static_cast<int >(sizeof (m_buf)); i++)
{
cout << m_buf[i];
}
cout << endl;
}

};

void display (char* in_p, int in_len, char* in_name)
{
cout << in_name << " (buf-size = " << in_len << ") : ";
for (int i = 0; i < in_len; i++)
{
cout << in_p[i];
}
cout << endl;
}

int main()
{
SHOW (sizeof (Foo1));
SHOW (sizeof (Foo2));
char buf1[BUF_SIZE];
char buf2[BUF_SIZE];
memcpy(buf1, "abcdxyz1", sizeof (buf1));
memcpy(buf2, "abcdxyz2", sizeof (buf2));

Foo1* p1 = reinterpret_cas t<Foo1*>(buf1) ;
Foo2* p2 = reinterpret_cas t<Foo2*>(buf2) ;
cout << endl;
p1->display();
p2->display();
p2->display(-4);
Foo1 foo1;
Foo2 foo2;
memcpy(foo1.m_b uf, "qwertyu1", sizeof (foo1.m_buf));
memcpy(foo2.m_b uf, "qwertyu2", sizeof (foo2.m_buf));
cout << endl;
foo1.display();
foo2.display();

char* pch1 = reinterpret_cas t<char*>(&foo1) ;
char* pch2 = reinterpret_cas t<char*>(&foo2) ;

cout << endl;
display (pch1, BUF_SIZE, "pch1");
display (pch2, BUF_SIZE, "pch2");
display (pch2, BUF_SIZE + 4, "pch2");

return 0;

}
=============== ======
====== Run ======

sizeof (Foo1) = 8
sizeof (Foo2) = 12

Foo1 [0, 7] = abcdxyz1
Foo2 [0, 7] = xyz2€A
Foo2 [-4, 7] = abcdxyz2€A

Foo1 [0, 7] = qwertyu1
Foo2 [0, 7] = qwertyu2

pch1 (buf-size = 8) : qwertyu1
pch2 (buf-size = 8) : ₪!A qwer
pch2 (buf-size = 12) : ₪!A qwertyu2

=============== ==

Alex Vinokur
email: alex DOT vinokur AT gmail DOT com
http://mathforum.org/library/view/10978.html
http://sourceforge.net/users/alexvn

Nov 21 '06 #1
2 1836
You may not be sure that sizeof of all data + 4 bytes is sizeof of
whole instance, because there may be aligning and pointer is not always
4 bytes big.

reinterpret_cas t allows it, because reinterpret_cas t does almost
nothing. It only changes one pointer type to other pointer type without
any conversions. So you have to be sure you know what are you doing,
becasue you (as programmer) are taking the responsibility of the type
corectness here.

Nov 21 '06 #2
VJ
Alex Vinokur wrote:
classes that have virtual methods hold pointer to virtual table as
additional implicit data member. So, sizeof of such classes is sizeof
of all data (as struct-POD) plus 4.
It seems that use of casting for such classes is quite dangerous.
See sample below.

Why does reinterpret_cas t permit such a casting?

Besides:
h.cpp:24: warning: 'struct Foo2' has virtual functions but non-virtual
destructor

I dont see whats the problem.

Foo1* p1 = reinterpret_cas t<Foo1*>(buf1) ;
Try this:
int pch1 = reinterpret_cas t<int>(&foo1);
std::cout<<pch1 <<std::endl;
reinterpret_cas t transforms 1 type to another, and these two dont have
to related at all. With that command, you say to your compiler "shut up,
i know what I am doing"
Nov 21 '06 #3

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

Similar topics

6
6463
by: Stuart Golodetz | last post by:
Hi, I've got a minor casting issue which I need to check about (marked // <--). I was trying to do a static_cast on it (which didn't work, though I'm not sure why this should be the case?) I also tried reinterpret_cast (which is clearly an exceedingly dodgy thing to do; it worked, but I'm not sure whether it should have worked, or whether...
4
385
by: aap | last post by:
Hi, I have the following code. #include <iostream> using namespace std; class Root { public: virtual void Root1() = 0; virtual void Root2() = 0;
27
3815
by: Daniel Vallstrom | last post by:
I'm having problems with inconsistent floating point behavior resulting in e.g. assert( x > 0.0 && putchar('\n') && x == 0.0 ); holding. (Actually, my problem is the dual one where I get failed assertions for assertions that at first thought ought to hold, but that's not important.) At the end is a full program containing the above...
5
1660
by: zzppallas | last post by:
I have interface A and interface B decalared as follow: class A { public: virtual void OnError(std::string reson) = 0; }; class B { public:
8
2063
by: Herby | last post by:
Given class B and C which inherit from class A They all override a method of the form: Add( A^ lhs, A^ rhs ); So A is abstract. So if i was defining Add for class B : B::Add( A^ lhs, A^ rhs ) { Value = ((B)lhs)->Value + ((B)rhs)->Value;
2
461
by: Mike Stevenson | last post by:
Hi. I'm in the process of re-learning all the C++ I forgot from college, and I'm starting to get into some virgin (or at least only a couple times) territory. I have some questions about casting a pointer from a base class to a derived class. For example: class Base{ public: Base() {} virtual ~Base() {} void func1(int);
11
3419
by: Nindi73 | last post by:
A few days a ago I posted my code for a deep copy pointer which doesn't require the pointee object to have a virtual copy constructor. I need help with checking that it was exception safe and exception neutral/ I got a reply from Bux with his code for a smart pointer with far fewer lines of code and more cleaner design, not over engineered...
7
1770
by: v4vijayakumar | last post by:
Is it possible to implement member object's virtual functions, in the containing class? If not, is it possible to simulate this behavior? ex: class test { protected: virtual void fun() = 0; };
0
1796
by: akshaycjoshi | last post by:
I am reading a book which says Even though unboxed value types don't have a type object pointer, you can still call virtual methods (such as Equals, GetHashCode, or ToString) inherited or overridden by the type. The reason is because the CLR can just call these methods nonvirtually and System.ValueType overrides all of these virtual methods...
0
7804
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...
0
8156
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. ...
0
8310
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...
0
8180
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...
0
6563
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...
0
5366
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...
0
3809
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...
0
3832
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
1144
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...

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.