Can I call a derived class's function in base class?

127 views Asked by At

I have a function d() in a derived class, which is to be called in a base class function b(). I tried to do this by making a virtual function with the same name in the base class(to satisfy the compiler and to enforce late binding). I will always be calling the b() using an object of derived class. But the problem is that compilation goes fine, but linker is returning an error:

undefined symbol <baseclass_name>::d in module main.cpp   

the Weird thing is that d() is not even called in main.cpp. It is defined and called in another file.

I am stuck here. Can anyone give any possible explanations or suggest a better method?

(I need to call d() from base class or it will make my code even more bulky...)

3

There are 3 answers

0
Mike Seymour On

You'll need to either implement the base-class version, or declare it pure virtual in the base class (or both), depending on whether it makes sense for the base class to implement it. All non-pure virtual function must be implemented, which is probably why you get that error.

0
Jackzawa On

Template method pattern may help you, declare the function pure virtual on base class and implement it on the derived class. And use the function normally on base class.

0
Fozi On

I think your problem might not be C++ but linkage. If you put your d() in another cpp file you will have to compile and link those files together. For example:

g++ main.cpp a.cpp b.cpp -o test

This will compile the three .cpp files and link them together into the executable called 'test'.

If you are using an IDE you might have to create a project and add all required cpp files to it. When you build all the files in the project will be used to build your executable.