Search code examples
c++inheritancepolymorphismvirtualabstract

Accessing virtual class through the pointer


I have to design the specific architecture of the project. I got stuck while trying to create the pointer to the virtual class, and got Segmentation fault (seems my pointer was not assigned correctly). Below I included the draft of what I'm trying to do.

// Class A has to be pure virtual. It will be inherited by many classes in my project.
class A: 
{
public:
 virtual void myFunction() = 0; 
}


// Class B implements the method from the class A
#include <A.h>
class B: public A
{
public:
void myFunction(); // IS IMPLEMENTED HERE!!
}


// Class C creates a pointer to the class A.
 #include <A.h>
class C:
{
A *ptr;
ptr->myFunction();  //Here I want to run myFuction() from the class B.
}

How can I make a connection between those three, so I get the result I want. I can't change the architecture, or simply omit any of the classes A, B or C. Thanks for help!


Solution

  • The virtual calls allow to access a function from an object through a pointer or reference of a base type. Note that the object itself needs to be of the type that implements the functionality.

    So, in class C you can have something like:

    B b;
    A *ptr = &b;
    ptr->myFunction()
    

    or

    A *ptr = new B();
    ptr->myFunction()
    

    Either way, you need to create an object of type B, and assign it to a pointer of type A*.