Problem with inheritance

Dear all,
could anybody tell me what is wrong with the attached code? It gives a Bus Error at run time.

I need to do:

 
  C *c = (C*)(new A());


because I have a function which returns a pointer to an object of class A and I want to use it as an object of class C. The code works if class C inherits directly from A.

Thank you very much for your help,

Francesco


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
37
38
39
#include "stdio.h"

class A {

public:
  A() {};
  virtual ~A() {};

};

class B : public A {

public:
  B() : A() {};
  virtual ~B() {};
 
  virtual void Hello() = 0;

};

class C : public B {

public:
  C() : B() {};
  ~C() {};

  void Hello();

};

void C::Hello() { printf("hello\n"); }

int main(){

  C *c = (C*)(new A());

  c->Hello();

}
You can't (And really shouldn't!) do that.

A does not derive from C.
Instead, you can do the opposite, because C derives from A.

The reason behind this, is because Hello is virtual in B, while it is not in its base class (A).
Last edited on
Topic archived. No new replies allowed.