Converting between base and inherited class

Hello all,

Lets say for the sake of argument I have 3 classes, protocolA, protocolB and connect.

protocolB inherits from protocolA and has exactly the same interface. connect is a GUI connection dialog that takes a pointer to protocolA and runs ->connect() on that.

The problem I am having is that I don't know which protocol will be used until the user selects it in the connection dialog, so when the class is initialised before the GUI is even created, it is created as a protocolA.

My question is, is it possible to convert the pointer from protocolA to protocolB in the connect class if so required?

Note that it is accessed through pointers in the entire program, including main where it is created using new.


If this isn't possible, can anyone suggest a better solution?

Thanks.
This doesn't seem like the best solution.

I think you need to have a single parent. And then 2 children and only instantiate the one you need at runtime.

e.g
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
31
32
33
34
35
36
#include <iostream>

using namespace std;

class parent {
public:
  virtual void print() = 0;
};

class childA : public parent {
public:
  void print() { cout << "Child A" << endl; }
};

class childB : public parent {
public:
  void print() { cout << "Child B" << endl; }
};

void callPrintOnClass(parent *target) {
  target->print();
}


int main() {

  childA *A = new childA();
  childB *B = new childB();

  //parent *p = new parent(); // Error -> Cannot instantiate abstract class

  callPrintOnClass(A);
  callPrintOnClass(B);

  return 0;
}

Thanks Zaita, I think what I'll do is set up a new namespace and just copy all the functions in, adding the parent as the first argument.

Just a quick question, what does the '= 0' do on the virtual function declaration? I have not seen that before.
= 0 means pure-virtual. This means the parent class will not have an implementation of it. All child classes MUST inherit and override this method.

That is why you cannot create an instance of parent.

Topic archived. No new replies allowed.