Converting a class

Jun 11, 2008 at 1:13am
Hello, I need to know how one would convert a Base Class to a class derived from it.

1
2
3
4
5
6
7
8
9
bool convert = true;

Base_class *Object;

	
if(convert)
{
    Object = new derived_class;
}


I was thinking something like this, although I'm not too sure if this works.

also any tutorials would be helpful as I'm just learning to code in C++

Thank You.
Jun 11, 2008 at 1:18am
 
Object = (Derived*)derived_class;


Thats the QaD (Quick and Dirty) way to do it.
Jun 11, 2008 at 1:44am
What would be in place of

Object = (Derived*)derived_class;

also what is that called? type casting?
Jun 11, 2008 at 7:16am
The 'correct' way is
 
Object = dynamic_cast<Base_class *>(derived_class);

and yes this is type casting, see this for more info
http://www.cplusplus.com/doc/tutorial/typecasting.html
Jul 26, 2008 at 11:26am
Your first version was correct. No need to use cast operators, the cast from derived to base class is absolutely legal. In the opposite case if you want to cast from base to derived type, you can use either static_cast or dynamic_cast. The difference is dynamic_cast guarantees safe casting and if something is wrong it returns a NULL pointer, and static_cast performs no any checks before casting, and can bring to runtime errors. Note, that dynamic_cast can be used for classes containing virtual function table, i.e. you should have at least one virtual function in base class.

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
30
class Base {
    ...........
private:
    virtual void f();
};

class Derived1 : public Base {
    ...........
public:
    void func1();
};

class Derived2 : public Base {
    ...........
public:
    void func2();
};

// global function
void exec(Base * pb)
{
    Derived *pd = dynamic_cast<Derived1>(pb);
    if (0 != pd) { // here you exactly know that the argument
                        // was of Derived1 type, and can call its member
        pd->func1();
    } else { // pb is of Derived2 type
        pd = static_cast<Derived2>(pb);
        pd->func2();
    }
}


Last edited on Jul 26, 2008 at 11:35am
Topic archived. No new replies allowed.