Search code examples
c++staticnew-operatormultiple-inheritance

Parenthesis before the new operator - meaning?


For a child class I have the following code:

class child1 : public parent {
public:
    static parent* function1(void) {
        return (child2*) new child1;
    }
    //...
};

Child2 is a other class that inherits from the parent.

What is the significance of using the parenthesis before the new operator i.e. (child2*)?
What's the best way to explain what the function does?


Solution

  • return (child2*)new child1;
    

    That is a C-style cast. It casts the pointer from child1 * to child2 *

    If you intend to cast this from one kind of pointer to another, you should use the dynamic_cast keyword instead.

    return dynamic_cast< child2 * >( new child1 );
    

    C++ provides several casts to make it obvious what kind of cast you intend. It provides dynamic_cast for polymorphic casting (i.e. - does have a vtable), static_cast for casting objects that are not polymorphic (i.e. - doesn't have a vtable), reinterpret_cast to tell the compiler to consider the bytes within the object as a different kind of object, and const_cast to cast away constness or volatile-ness (or cast into a const or volatile object).

    Many C++ programmers will never use C-style casts since the syntax of it provides no clue what you intend.

    You should also know whether child1 and child2 are related. One should be a derived class of the other. If not, the dynamic_cast will return a nullptr.