2

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!

Yyomi
  • 23
  • 3
  • 8
    `A* ptr = new B`? It seems you could use [a good book or two to read](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), to freshen up on C++. – Some programmer dude Jul 17 '19 at 11:57
  • All your declarations are wrong, this cannot compile. And `A *ptr; ptr->myFunction();`: `ptr` points nowehere so a segfault is somewhat expected. – Jabberwocky Jul 17 '19 at 11:59
  • 4
    _"seems my pointer was not assigned correctly"_ It wasn't assigned (initialised) _at all_! – Lightness Races in Orbit Jul 17 '19 at 11:59
  • Learn what [polymorphism](https://www.geeksforgeeks.org/polymorphism-in-c/) is in C++. Also try not to use raw pointers. In this case it seems like you can use [unique_ptr](https://en.cppreference.com/w/cpp/memory/unique_ptr) – SubMachine Jul 17 '19 at 12:11
  • `// IS IMPLEMENTED HERE!!`: no it is not, it is only declared. – YSC Jul 17 '19 at 12:29

1 Answers1

1

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*.

Paul92
  • 8,827
  • 1
  • 23
  • 37
  • Dear Paul, Thank you very much for the kind and instructive response. The second solution was exactly what I was looking for! – Yyomi Jul 17 '19 at 13:08