473,386 Members | 1,702 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,386 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 3287

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 { ...
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
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:
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
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
0
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,...

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.