0

The following code represents my problem.

// File1.h
class A {
    public:
        void print() {
            printf("This is class A.");
        }
}

// File2.h
#include "File1.h"
class B: public A {
    public:
        void print() {
            printf("This is class B.");
        }
}

// File3.h
#include "File1.h"
void printClass(void* obj) {
    A* aObj = (A*) obj;
    aObj->print();
}

// Main.c
#include "File1.h"
#include "File2.h"
#include "File3.h"
void main(int argc, char* argv[]) {
    B* bObj = new B;
    printClass(bObj);
}

The output is "This is class A." I need it to print "This is class B".

I know this seems dumb, but due to restrictions with my actual code I need to cast void objects which may be of type B to objects to type A. File 3 does not know about class B. Explanation is that this is a framework in which I expect people make their own derived classes of A and then pass objects of it to the framework, therefore the framework does not know what it will get other than it's a derived class of A.

And it has to hold an object of B as void because I'm using a generic linked list, with nodes that hold void* pointers, the same linked list is used in many places so I've kept it generic.

Is there a way to do this?

  • 1
    `virtual void print()` – Rabbid76 Oct 14 '18 at 14:30
  • Read [`Why do we need virtual functions in C++?`](https://stackoverflow.com/questions/2391679/why-do-we-need-virtual-functions-in-c) – Rabbid76 Oct 14 '18 at 14:31
  • Why bother with the `void*` song and dance at all? – George Oct 14 '18 at 14:32
  • Ah thank you so much! Didn't know about virtual functions, coming from a C background. – Ernest Placido Oct 14 '18 at 14:34
  • 1
    If you come from a C background and want to learn C++, the best advice I can give you is *forget everything you know about C and start with modern C++ from scratch*. Modern C (C11) and modern C++ (in the form of C++17) are so radically different that to write *good* code in either you can't use anything (almost) you know about the other. – Jesper Juhl Oct 14 '18 at 14:43
  • Thanks, this has definitely taught me that I need to do deeper research into C++ rather than getting by with my knowledge of C. – Ernest Placido Oct 14 '18 at 15:01

0 Answers0