Hi,
I have been trying to understand this concept for quite sometime now
somehow I am missing some vital point. I am new to Object Oriented
Programming so maybe thats the reason.
I want to understand what is typecasting in C++. Say I have a Base
class and a Derived class, I have a pointer to an object to each.
Base *ba = new Base;
Derived *de = new Derived;
Now when I do something like
Base *one = (Base*)de;
What is really happening here ? "de" was an object of class Derived
and had data specific to that class. Now by typecasting I have access
to all the functions and data of the Base class but where is the data
of my Derived class object , I no longer have access to it, if I do
one-> ....(derived class data)
Thanks,
Kapil
#include "stdafx.h"
// Using pragmas to see the difference in programs in binary level
using namespace std;
class Base
{
public:
int a,b;
void print();
};
class Derived : public Base
{
public:
int c,d;
void print();
};
void Base::print()
{
cout << "In Base" << endl;
}
void Derived::print( )
{
cout <<"In Derived" << endl;
}
int main()
{
Base ba;
Derived de;
Base *a = new Base; // a is a pointer to the Base object
Derived *b = new Derived; // b is the pointer to the Derived object
Base *c = (Base*)b;
c->print();
Derived *d = (Derived*)b;
d->print();
} 3 8185
"Kapil Khosla" <kh*********@ya hoo.com> wrote... I have been trying to understand this concept for quite sometime now somehow I am missing some vital point. I am new to Object Oriented Programming so maybe thats the reason.
I want to understand what is typecasting in C++. Say I have a Base class and a Derived class, I have a pointer to an object to each.
Presumably, 'Derived' is actually derived from 'Base', right?
Base *ba = new Base; Derived *de = new Derived;
Now when I do something like Base *one = (Base*)de;
No cast is necessary. Conversion from a derived to its base
is implicit. You may write
Base *one = de;
What is really happening here ? "de" was an object of class Derived and had data specific to that class.
Well, 'de' wasn't an object. 'de' is a pointer to an object.
Now by typecasting I have access to all the functions and data of the Base class but where is the data of my Derived class object , I no longer have access to it, if I do one-> ....(derived class data)
What happens when you convert a pointer to a derived class to
a pointer to a base class, the compiler computes the location
of the base subobject in the derived object and returns the
address of that subobject.
de ---> +------------------+
| Derived object |
one ---> +------------+ |
| | Base | |
| | subobject | |
| +------------+ |
| |
+------------------+
And, no, you don't have access to 'de's data through 'one'
simply because they are different objects.
Victor
"Kapil Khosla" <kh*********@ya hoo.com> wrote in message
news:91******** *************** ***@posting.goo gle.com... Hi, I have been trying to understand this concept for quite sometime now somehow I am missing some vital point. I am new to Object Oriented Programming so maybe thats the reason.
I want to understand what is typecasting in C++. Say I have a Base class and a Derived class, I have a pointer to an object to each. Base *ba = new Base; Derived *de = new Derived;
Now when I do something like Base *one = (Base*)de;
This cast is not needed. In fact it bad style to cast here. All you need is
this
Base *one = de; What is really happening here ?
Nothing. I mean that, nothing is happening. You are assigning one pointer to
another, that is all.
"de" was an object of class Derived and had data specific to that class. Now by typecasting I have access to all the functions and data of the Base class
No. You had access to those already.
but where is the data of my Derived class object , I no longer have access to it, if I do one-> ....(derived class data)
You cannot access the derived data using ba, its still there however and you
can access it though de. ba and de are pointing to the same object, but be
only 'sees' the Base part of it. You can still access the Derived object
through the Base pointer using virtual functions however. Thanks, Kapil
You clearly have a long way to go before understanding casting. usually when
people get stuck like this it is because they think things are more
complicated than they are. Its really very simple.
class Animal
{
};
class Monkey : public Animal
{
};
All Monkeys are Animals. So it must be legal to a Monkey pointer to an
Animal pointer. This can be done without a cast.
Monkey m;
Monkey* mp = &m;
Animal* ap = mp; // this is OK, no cast necessary
Now both mp and ap are pointing to (the same) monkey.
But only SOME animals are monkey, so to assigning an animal pointer to a
monkey, is not safe. Because of this if you want to convert an Animal
pointer to a Monkey pointer, you must use a cast.
Monkey m;
Animal* ap = &m; // no cast necessary
Monkey* mp = (Animal*)ap; // cast necessary
Again, both ap and mp are now pointing at the same monkey.
Any more questions please ask. You're clearly misunderstandin g something,
but it hard for us to tell exactly what.
john
"Rolf Magnus" <ra******@t-online.de> wrote in message
news:bf******** *****@news.t-online.com... John Harrison wrote:
class Animal { };
class Monkey : public Animal { };
All Monkeys are Animals. So it must be legal to a Monkey pointer to an Animal pointer. This can be done without a cast.
Monkey m; Monkey* mp = &m; Animal* ap = mp; // this is OK, no cast necessary
Now both mp and ap are pointing to (the same) monkey.
But only SOME animals are monkey, so to assigning an animal pointer to a monkey, is not safe. Because of this if you want to convert an Animal pointer to a Monkey pointer, you must use a cast.
Monkey m; Animal* ap = &m; // no cast necessary Monkey* mp = (Animal*)ap; // cast necessary
ITYM:
Monkey* mp = (Monkey*)ap; // cast necessary
Yes of course, thanks for the correction. Again, both ap and mp are now pointing at the same monkey.
But please don't use C style casts. Use the newer C++ casts, in this case static_cast or dynamic_cast. C style casts don't have the fine-grained control over what exactly is done that the C++ casts have, which makes them more error-prone (e.g. casting away const by accident). In the above example, you can either write:
Monkey* mp = static_cast<Mon key*>(ap);
This does (in this case) the same as the above C style cast, but you should only write this if you are _absolutely_ sure that ap actually points to a Monkey, since there is no way to check if the resulting pointer is valid (and it only is if the object pointed to by ap actually is a Monkey). For dynamic type checking, use a dynamic_cast:
Monkey* mp = dynamic_cast<Mo nkey*>(ap);
The resulting pointer will either point to the object, or, if that object isn't a Monkey, it will be a null pointer. Note that dynamic_cast only works if your base class is polymorphic, i.e. it has at least one virtual member function.
All true, but the OP posted his question using C style casts, and since he's
clearly having trouble with those, I thought one concept at a time would be
a better approach.
john This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Nicolay Korslund |
last post by:
Hi! I'm having a little trouble with the typecast operator, can anybody
help me with the rules for when the this operator is invoked?
In the class 'Test' in the code below, the typecast operator returns a
'mytype'. In main() I use the operator on 'Test'-class objects. If
'mytype' is a pointer the operator works fine. But if I instead try
to call an overloaded operator, the typecast operator is not invoked,
and I get a compiler error...
|
by: Arun Prasath |
last post by:
Hi all,
I have the following question regd pointer typecasting. Is the
following type of pointer typecasting valid?
#define ALLOC(type,num) ((type *)malloc(sizeof(type)*num))
/*begin code*/
|
by: andynaik |
last post by:
Hi,
Whenever we type in this code
int main()
{
printf("%f",10);
}
we get an error. We can remove that by using #pragma directive t
direct that to the 8087. Even after that the output is 0.00000 and no
10.0000. Can anybody tell me why it is like that and why typecasting i
not done in this case?
|
by: Vinod Patel |
last post by:
I have a piece of code : -
void *data;
......
/* data initialized */
......
struct known_struct *var = (struct known_struct*) data; /*typecasting*/
How is this different from simple assignment.
int b = some_value;
|
by: jdm |
last post by:
In the sample code for the SortedList class, I see the use of a string
typecasting macro consisting of a single letter "S". i.e.:
Sortedlist->Add(S"Keyval one", S"Item one");
Now I have deduced that the "S" can be replaced with (String __gc *) and the
code will compile and run just fine. But what I can't find is what exactly
Microsoft calls these macros (I have also seen "L" used the same way) and
where they are all documented. I...
| |
by: Raghu |
last post by:
Hello All,
I need some help regarding overloading operation.
Is there any way to overload typecasting?
I mean if i have a piece of code as below.
int a = 2:
float b;
b = (float)a;
|
by: Abhishek |
last post by:
why do I see that in most C programs, pointers in functions are
accepted as:
int func(int i,(void *)p) where p is a pointer or an address which is
passed from the place where it is called. what do you mean by pointing
to a void and why is it done?
Aso, what happens when we typecast a pointer to another type. say for
example int *i=(char *)p;
under different situations? I am kind of confused..can anybody clear
this confusion by clearly...
|
by: ramakanta.sinha |
last post by:
Hi,
While typecasting an integer to (void *) the following warning
is found.
warning: cast to pointer from integer of different size.
This is the line where typecasting is done.
fld->base = (void *)(((fld->f90_table_index-1) *
F90_MAX_FLD_SIZE_IN_BYT
|
by: bwaichu |
last post by:
What is the best way to handle this warning:
warning: cast from pointer to integer of different size
I am casting in and out of a function that requires a pointer type. I
am casting an integer as a pointer, but the pointer is 8 bytes while
the integer is only 4 bytes.
Here's an example function:
|
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...
|
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,...
| |
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...
|
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...
|
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,...
|
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...
|
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
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
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...
| |