Casting non pointers

Hello.
In http://www.cplusplus.com/doc/tutorial/typecasting/ you find the following example for casting a pointer.

1
2
3
    Base * pba = new Derived;
    Derived * pd;
    pd = dynamic_cast<Derived*>(pba);

Is it possible and correct to cast a non pointer instance?
I am looking for something like that:

1
2
3
    Base pba = Derived();
    Derived pd;
    pd = (Derived) pba;

Thank you.
There is 'polymorphism' where you can treat a pointer to a child class as if it were a pointer to it's parent.

EDIT: Links would probably help wouldn't they? http://www.cplusplus.com/doc/tutorial/polymorphism/
Last edited on
Aside from pointer, you can cast a reference:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

class A
{
public:
    virtual void foo()
    {
        std::cout << "A";
    }
};

class B: public A
{
public:
    virtual void foo()
    {
        std::cout << "B";
    }
};

int main()
{
    B x;
    A& y = x;
    B z = dynamic_cast<B&>(y);
    x.foo();
    y.foo();
    z.foo();
}
BBB
But this
1
2
A a;
B b = dynamic_cast<B&>(a);
will lead to exception.
Yes, I read the content on the first link, but still have some doubts.

About MiiNiPaa's answer:
Which is the difference between
A& y = x;
and
A* y = &x;
?
I mean, if I'm not wrong A* means a pointer, so y would be a point to x in second statement.
What is y in first statement then? The same?

Thank you.
@ OP: Do you have doubts about the validity of the article? Or do you mean to say that you still have questions?
MiiNiPaa: the links are perfect. I think I didn't find this explanation on cplusplus.com.

Computergeek01: I meant I still had questions. Of course I'm not questioning the validity of the article. Sorry I explained bad.

Thank you.
Topic archived. No new replies allowed.