473,839 Members | 1,465 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Using Ptr of derived class to point to base class and viceversa

Using Ptr of derived class to point to base class and viceversa
class base
{
....
}
class derived : public base
{
....
}

I want to know any practical scenario when this is used
a. B b;
D *p = &b;

b. B *b;
D d;
b = &d;

Can any one explain it?I know it is theoritically OK.But i am not able
why to do such things?

Thanks in Advance,
Bhanu

Sep 19 '05 #1
10 3338

Bhan wrote:
Using Ptr of derived class to point to base class and viceversa
class base
{
...
}
class derived : public base
{
...
}

I want to know any practical scenario when this is used
a. B b;
D *p = &b;

b. B *b;
D d;
b = &d;

Can any one explain it?I know it is theoritically OK.But i am not able
why to do such things?
doesnt this lead to the Slicing Problem ?

Thanks in Advance,
Bhanu


Sep 19 '05 #2
placid wrote:
Bhan wrote:
Using Ptr of derived class to point to base class and viceversa
class base
{
...
}
class derived : public base
{
...
}

I want to know any practical scenario when this is used
a. B b;
D *p = &b;
No practical use of downcasting from an object not of the derived type.

b. B *b;
D d;
b = &d;
Upcasting: Happens all the time.

Can any one explain it?I know it is theoritically OK.But i am not able
why to do such things?

doesnt this lead to the Slicing Problem ?


Slicing happens when you copy the object. The OP is simply taking
pointers to the object.
Sep 19 '05 #3
So you mean this is normally used?
Upcasting: Happens all the time.


B b;
D *p = &b;
But why do this ?why not have a ptr to base class itself ?(below)

B b;
B *p = &b;

Can you give the use of these two?
B b;
B *p = &b;
D *p = &b;

Sep 19 '05 #4
"Bhan" <sw*******@gmai l.com> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.com
Using Ptr of derived class to point to base class and viceversa
class base
{
...
}
class derived : public base
{
...
}

I want to know any practical scenario when this is used
a. B b;
D *p = &b;
You shouldn't do this because the derived class will usually have members
that the base class does not. The derived class pointer will allow you to
try to access members of the derived class than don't exist in the base
class object, with possibly disastrous consequences.
b. B *b;
D d;
b = &d;


This is safe and very useful, though it rarely occurs in the context that
you have shown. It occurs in two main contexts.

1. Containers of pointers. The container (an array or vector or whatever)
can usually only store pointers of a single type. If you want it to point to
both base and derived class objects, then you store base pointers and assign
to those base pointers the addresses of both base and derived class objects.
You can then iterate over all the members in the container, calling the same
function for each. If the function is virtual, then you can get a different
function for the pointers pointing to the derived class objects as compared
to the pointers pointing to the base class objects (this is known as
run-time polymorphism). For non-virtual functions, you get the same function
in both cases, but this is OK since the function is a member of both the
base and the derived class (with public inheritance, any public function in
the base class becomes a public function in the derived class).

2. Functions that take pointer arguments. Given, say:

Base b;
Derived d;

void foo(Base *ptr)
{
ptr->MemberFunction ();
}

you can call this function using the address of either a base class or a
derived class object:

foo(&b);
foo(&d);

The effect of the first is:

ptr = &b;
ptr->MemberFunction ();

The effect of the second is:

ptr = &d;
ptr->MemberFunction ();
--
John Carson

Sep 19 '05 #5
b. B *b;
D d;
b = &d;

Can I summarize my understanding like this?

Whenever you have the provision to store only base ptr,store the base
ptr that points to dervied object.

When u retrieve it,use static_cast and get the req derived object.Right?

Sep 19 '05 #6
Bhan wrote:
b. B *b;
D d;
b = &d;


Can I summarize my understanding like this?

Whenever you have the provision to store only base ptr,store the base
ptr that points to dervied object.

When u retrieve it,use static_cast and get the req derived object.Right?


static_cast if you are sure that the pointer points to the derived
class. Use dynamic_cast if you are not sure and you have a polymorphic
base class.

john
Sep 19 '05 #7
"Bhan" <sw*******@gmai l.com> wrote in message
news:11******** **************@ f14g2000cwb.goo glegroups.com
b. B *b;
D d;
b = &d; Can I summarize my understanding like this?

Whenever you have the provision to store only base ptr,store the base
ptr that points to dervied object.


Yes.
When u retrieve it,use static_cast and get the req derived
object.Right?


Most of the time you don't need any cast. You call functions that are
declared in the base class and may or may not be virtual.

If you want to call a derived class function that does not exist in the base
class --- or does exist but is not virtual --- then a cast is necessary. See
John Harrison's remarks on this.

Note that these issues only arise in situations where you don't
automatically know the type of object pointed to, as with a container of
pointers that can point to both base and derived class objects. In such
contexts, it is simplest if you can make the same function call regardless
of what the pointer points to and you achieve different behaviour by using
virtual functions. Having to figure out what is pointed to --- and making
different function calls on that basis --- is inelegant and error prone.

If you have derived objects and only derived objects and you know it, then
you just use pointers to derived objects (if you use pointers at all) and
none of these complications arise.

--
John Carson

Sep 19 '05 #8
Bhan wrote:
b. B *b;
D d;
b = &d;

Can I summarize my understanding like this?

Whenever you have the provision to store only base ptr,store the base
ptr that points to dervied object.

When u retrieve it,use static_cast and get the req derived object.Right?


One thing to remember of course is that a pointer to a derived class is
also a pointer to the base class. It can be used anywhere a base class
pointer can be used. An instance of the derived class is an instance of
the base class.

And while "downcasts" from a base class to a derived class are
sometimes necessary, using them is not considered a good programming
practice. A lot of downcasts in source code generally indicate a
weakness in the program's class hierarchy or implementation. After all,
if the client has a base pointer it should not need to "know" about its
derived classes. That is the whole point of having an abstraction in
the first place. On the other hand if a client does need an object of
the derived class for some reason, then the question becomes how did it
wind up with a pointer to the base class.

Greg

Sep 19 '05 #9
Thats fine.
I am satisfied with this.
So,Can I summarize my understanding like this?
Whenever you have the provision to store only base ptr,store the base
ptr that points to dervied object.
When u retrieve it,use dynamic_cast or static_cast(dep ending on the
situation)and get the req derived object.Right?

Thanks
Bhanu

Sep 19 '05 #10

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

Similar topics

4
3110
by: Gopal-M | last post by:
I have the problem with sizeof operator I also want to implement a function that can return size of an object. My problem is as follows.. I have a Base class, say Base and there are many class derived from it. At a particular point in my application I need the size of the object pointed to by the base pointer. Eg
24
3312
by: Shao Zhang | last post by:
Hi, I am not sure if the virtual keyword for the derived classes are required given that the base class already declares it virtual. class A { public: virtual ~A();
1
16250
by: ypjofficial | last post by:
Dear All, According to OOPs , a base class pointer can to point to derived class object....call this as fact1 But somehow I am not comfortable while understanding this concept. The explanaition to the fact1 is given as since the derived object always consists of the base part , the base class pointer will always point to the base part in the derived object unless otherwise the function in the base class are declared as virtual and are...
11
19464
by: z_learning_tester | last post by:
Hello, yes another beginner question that I'm sure is obvious to many here :-) My book is so bad. Really. It uses the exact same example of code for using the new kw and for using virtual(in the base class) then override(in the derived class), but fails to compare and contrast the two... I've read this (short snippet)three times and by the looks of it they both do exactly the same thing- allow you to derive from the base and save...
3
2009
by: flat_ross | last post by:
For anyone who is just getting into VB.NET and/or is starting to work with inheritance I would like to point out a potential pitfall. We found this confusion recently when code-reviewing an application. If you have not used the keyword 'Overridable' then read on for sure... If you setup a child class and you want to override a method in your base class, you may see the squiggles under your child's method name. The pop-up/build error says...
31
2922
by: anongroupaccount | last post by:
I have an ABC with a protected member that is a reference to an object of an ABC type: class ABC { public: virtual ~ABC() = 0; protected: AnotherABC& _member; }
5
1963
by: Michael | last post by:
Hi, Could you tell me whether the following two statement are the same? Derived class is derived from Base class. 1. Base* ptr1; 2. Derived * ptr2; Does it mean ptr1 is the same as ptr2?
6
2946
by: ivan.leben | last post by:
I want to write a Mesh class using half-edges. This class uses three other classes: Vertex, HalfEdge and Face. These classes should be linked properly in the process of building up the mesh by calling Mesh class functions. Let's say they point to each other like this: class Vertex { HalfEdge *edge; }; class HalfEdge { Vertex* vert;
1
2798
by: subramanian100in | last post by:
Consider class Base { .... }; class Derived : public Base { ...
0
10908
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10586
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
10648
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,...
0
10293
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7828
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
7017
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
5682
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...
0
5866
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
3
3134
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.