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

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 3282

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*******@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.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*******@gmail.com> wrote in message
news:11**********************@f14g2000cwb.googlegr oups.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(depending on the
situation)and get the req derived object.Right?

Thanks
Bhanu

Sep 19 '05 #10
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?


If I understand you correctly, I don't think your statement is
accurate. You shouldn't always refer to a derived class with a base
class pointer just because you can do so. Certainly, one of the main
reasons for using inheritance is to allow abstraction from the
specifics of derived classes, but this is generally done by using
virtual functions to create interfaces for the derived classes to
implement.

Casting back to the derived type from a pointer to the base class is
generally discouraged. If you need to refer to the derived object as
the derived type, not as the more general base type, then generally
speaking you should not be using a pointer to the base class at that
point in the code.

Consider:

// Abstract base class; cannot be instantiated
struct Shape { virtual void Draw() const = 0; }

// A concrete class
struct Square : public Shape
{
Square( float length ) : length_( length ) { /* ... */ }

// Implement the virtual function
void Draw() const { /*...*/ }

// An additional function that applies to Squares
void Rotate( float angle ) { /*...*/ }

private:
const float length_;
};

// Another concrete class
struct Circle : public Shape
{
Circle( float radius ) : radius_( radius ) { /* ... */ }
void Draw() const { /*...*/ }
private:
const float radius_;
};

Now you can use the base classes to refer to the derived classes and no
cast is needed:

void Foo( const Shape& shape )
{
// ...
shape.Draw();
// ...
}

We could pass a Circle or a Square into this function. If we needed to
call Square::Rotate(), we should probably not do so from Foo since
Shape (and its subclass Circle) does not support the Rotate operation.
The design should be altered so that the object we have is guaranteed
to be a Square, e.g.,

void Bar( Square& square )
{
// ...
square.Rotate( 20.5 );
Foo( square );
// ...
}

You might be interested in the FAQ for this group, which as several
sections on inheritance:

http://www.parashift.com/c++-faq-lite/

Cheers! --M

Sep 19 '05 #11

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

Similar topics

4
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...
24
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
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...
11
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...
3
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...
31
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
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
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...
1
by: subramanian100in | last post by:
Consider class Base { .... }; class Derived : public Base { ...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
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...

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.