// In Common.hpp
#include <iostream>
using namespace std;
class Common
{
public:
Common( ) { };
virtual ~Common( ) { };
virtual void func()
{
std::cout << "This is Common\n";
genericPtr->XYZ(); /// If A is instantiated than genericPtr should become A class ptr or else B class ptr
};
};
// In B.hpp
#include "Common.hpp"
class B : public Common
{
public:
B( ) { };
virtual ~B( ) { };
void XYZ( ) { printf("I am B\n"); };
};
// In A.hpp
#include "Common.hpp"
class A : public Common
{
public:
A( ) { };
virtual ~A( ) { };
void XYZ( ) { printf("I am A\n"); };
};
// Random.cpp
#include "A.hpp"
int main()
{
A *a = new A();
}
For example, I am instantiating A in Random.cpp file. Now by calling 'func()' from Random.cpp file, I want to print 'I am A', how to do that? Also I am not sure if the instantiation is correct. I could be Common *a = new A();, I am not sure about it.
The most important part is I want to know about the genericPtr in 'func', how does genericPtr know which class has been instantiated? What code should I write so that genericPtr knows that class A has been instantiated and it has to call XYZ() method of class A and not class B?
EDIT: Some kind of RTTI method if it could be used?