473,378 Members | 1,119 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,378 software developers and data experts.

Understanding Typecasting in C++

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();
}
Jul 19 '05 #1
3 8141
"Kapil Khosla" <kh*********@yahoo.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
Jul 19 '05 #2

"Kapil Khosla" <kh*********@yahoo.com> wrote in message
news:91**************************@posting.google.c om...
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 misunderstanding something,
but it hard for us to tell exactly what.

john
Jul 19 '05 #3

"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<Monkey*>(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<Monkey*>(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
Jul 19 '05 #4

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

Similar topics

7
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...
2
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...
63
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...
11
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...
3
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...
7
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;
16
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...
1
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...
12
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...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
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: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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.