Search code examples
c++pointerscastinguser-defined-types

Changing between user defined classes at runtime in C++


I have two classes with one extending the other. They both have a method called doSomething() that perform something different. I want to be able to have one pointer that I can switch from class A to class B and have the rest of the code run the same because they each have the same method name. Is this possible and is this the correct way to do it? Also, I'm pretty new to C++ so it could be just a problem with that.

class A {
    void doSomething()
    {
        // does something
    }
};

class B: public A {
    void doSomething()
    {
        //does something else
    }
};


main()
{
    A *ptr = new A;
    B *bptr = new B;

    // a giant loop

    ptr->doSomething();


    if(condition) 
    {
        ptr = bptr;
    }
}

Solution

  • What you are trying to achieve is called polymorphism. In C++, you will need to define a common (possibly abstract) base class C for A and B, make doSomething a virtual function, override it in both A and B, and make pointers of type C*. Here is a good introductory article on the topic.