473,385 Members | 1,465 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

How does a static_cast work?

When I static_cast a Derived object to a base object and call a print function with a base pointer, I still am getting the print function from Derived. I am a little confused as I was expecting base class print function.

Expand|Select|Wrap|Line Numbers
  1. #include <cstdlib>
  2. #include <iostream>
  3.  
  4. using namespace std;
  5. class Base
  6. {
  7.         int i;
  8. public:
  9.         Base()
  10.         {
  11.                 std::cout<<"Base Constructor"<<endl;
  12.         }
  13.         Base(const Base &)
  14.         {
  15.                 std::cout<<"Base Copy Constructor"<<endl;
  16.         }
  17.         virtual ~Base()
  18.         {
  19.                 std::cout<<"Base Destructor"<<endl;
  20.         }
  21.         virtual void print()
  22.         {
  23.                 std::cout<<"Its Base"<<endl;
  24.         }
  25.         virtual void print_s ()
  26.         {
  27.              std::cout << "Its Base print_2" << endl;
  28.         }
  29. };
  30.  
  31. class Derived : public Base
  32. {
  33. public:
  34.         Derived()
  35.         {
  36.                 std::cout<<"Derived Constructor"<<endl;
  37.         }
  38.         Derived(const Derived &)
  39.         {
  40.                 std::cout<<"Derived Copy Constructor"<<endl;
  41.         }        
  42.         virtual ~Derived()
  43.         {
  44.                 std::cout<<"Derived Destructor"<<endl;
  45.         }
  46.         void print()
  47.         {
  48.                 std::cout<<"Its Derived"<<endl;
  49.         }
  50.         void print_s ()
  51.         {
  52.              std::cout << "Its Derived print_2" << endl;
  53.         }        
  54. };
  55.  
  56. int main(int argc, char *argv[])
  57. {
  58.  
  59.         Base* b = new Derived;
  60.         Base* bptr = new Derived;
  61.  
  62.  
  63.         (*bptr) = static_cast<Base>(*b);
  64.         bptr->print();
  65.  
  66.  
  67.         return 0;
  68. }
Jul 6 '10 #1
4 5833
Banfa
9,065 Expert Mod 8TB
While you did down cast a derived object into a base object you then copied it into derived object before calling print on that object.

The object you copied it into was not changed, in fact can not change. So when you called print it called the derived print.

To call base::print from a derived object pointer you can use
bptr->Base::print();
To verify that static_cast does properly down cast to a base object you can try
static_cast<Base>(*b).print();
Jul 6 '10 #2
weaknessforcats
9,208 Expert Mod 8TB
This is not going to work.

When you cast a derived object to a base object, the derived portion gets chopped off so all you get is the base part of your derived object.

This is called slicing and is bad news.

The object still has the virtual functin table of a derived object. When you call a virtual function that uses data from the drived object you crash because the derived portion of the object was chopped off by the cast.

You are supposed to use static_cast to cast a pointer to a derived object to a pointer to a base object.

BTW: You have a memory leak by re-using a pointer to a new Derived without deleting the object first.
Jul 6 '10 #3
I agree that this is bad, and there is definitely a memory link. I was just trying to understand what actually happened.

Are we saying that the vptr of the objects are not changed even though the object is down cast in this case? So, it still points to the derived vtable.

In that case, it should crash if I accessed any data members of the derived class.
Jul 7 '10 #4
weaknessforcats
9,208 Expert Mod 8TB
A copy of your derived object is made. This copy is a base object. The base object does not have any of the derived objects members. Therefore, it is not a real copy. Instead it is a truncated zombie copy.

A cast in C++ means a) you are calling some legacy C function with void* arguments or somesuch, or b) your C++ design is screwed up.

static_cast is intended to copy a pointer to a new type provided the new type is in the hierarchy of the original type. static_cast taskes your word on this. dynamic_cast is the same as static_cast except the new type is verified at run time. That is:

Expand|Select|Wrap|Line Numbers
  1. //A is base B is derived
  2. A y;
  3. B x;
  4. A* ptr = static_cast<A*> (&x);
  5. B* ptr1 = static_cast<B*> (&y);
will result in ptr and ptr1 having an address whereas:

Expand|Select|Wrap|Line Numbers
  1. //A is base B is derived
  2. A y;
  3. B x;
  4. A* ptr = dynamic_cast<A*> (&x);
  5. B* ptr1 = dynamic_cast<B*> (&y);
will result in an address for ptr since you can always use a derived object as a base object but ptr1 will be null since you cannot use a base object as a derived object. That is, you cannot downcast in a hierarchy.

When you do need to downcast, you use the Hollwood Principle and construct a Template Method design pattern in your code.
Jul 7 '10 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

7
by: Jonas | last post by:
This works fine in Win XP but does not work at all in Win 98. Private WithEvents objIExplorer As InternetExplorer I have to do it like this to get it to work in Win 98 Dim objIExplorer As...
0
by: Miguel Cardenas | last post by:
Hello list For some strange reason `mysql_config --...` does not work. If try something like gcc -o progname `mysql_config --cflags` progname.c `mysql_config --libs` (NOTE:...
4
by: rick | last post by:
The following basic script works fine in firefox by not in IE. Can anyone spot the problem? In IE I can only delete the first line but not the lines created by javascript. Also, look at the HTML...
15
by: Generic Usenet Account | last post by:
While I have a very good feel for how inlining works, I fail to see how in the world inlining can work if the inlined function is not described "in place" in a header file, but rather defined in a...
2
by: Harry Haller | last post by:
Why does the following work: // (1) Set new cookies setcookie ("font_type", $type_sel, time()+3600); setcookie ("font_size", $size_sel, time()+3600); // (1) Get most recent cookie $font_type =...
0
by: Jarod_24 | last post by:
How does tabindex work in ASP .net pages I dosen't seem to work quite like in regular forms. and there isn't any TabStop property either. 1 .How do you prevent a control form beign "tabbed"....
6
by: Bob Day | last post by:
VS 2003 The documentation says " Nothing keyword represents the default value of any data type" this is simply not true and causing a lot of problems. 1) Consider an SQL table of 3 columns: ...
3
by: wwwmike | last post by:
For some reasons my HTTP Redirect for 404 errors does not work for certain files like .gif .jpg on IIS Version: 5.1, but it works perfectly with the VisualStudio2005 internal webserver ...
48
by: Jimmy | last post by:
thanks to everyone that helped, unfortunately the code samples people gave me don't work. here is what i have so far: <% Dim oConn, oRS, randNum Randomize() randNum = (CInt(1000 * Rnd) + 1) *...
4
by: Jon | last post by:
Hi, I used XslCompiledTransform with the following Xsl file. The <xsl:text disable-output-escaping="yes"does not work when using XslCompiledTransform to do the trnasform (namely the output...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.