I have two classes A and B that derive from an abstract class, Letter. At runtime, I would like to call a function that differs between the derived classes depending on the user input. The following code performs the functionality I want:
Letter.h:
#pragma once
#include <iostream>
class Letter
{
public:
virtual void PrintAlphabetPosition() = 0;
virtual ~Letter(){};
};
A.h:
#include "Letter.h"
class A : public Letter
{
public:
virtual void PrintAlphabetPosition() { std::cout << "1" << std::endl; };
virtual ~A(){};
};
B.h:
#include "Letter.h"
class B : public Letter
{
public:
virtual void PrintAlphabetPosition() { std::cout << "2" << std::endl; };
virtual ~B(){};
};
main.cpp:
#include <iostream>
#include "Letter.h"
#include "A.h"
#include "B.h"
void main() {
Letter* letter;
char input;
std::cin >> input;
if (input == 'A') {
letter = new A();
} else {
// Default to B
letter = new B();
}
letter->PrintAlphabetPosition(); // Prints 1 or 2 as expected
delete letter;
}
My question is, is there a way I can perform the functionality in main.cpp without instantiating A or B (not even a singleton)? Every single function I will have in these two classes will never depend on the particular instance of the class.
I considered turning A and B into 'static' classes by declaring all member functions and variables as static, and then hiding the constructor as private, similar to the answer to this question: How do you create a static class in C++?. However, the static declaration would conflict with the virtual declaration.
I also tried turning A and B into abstract classes by declaring PrintAlphabetPosition() as pure virtual functions too and moving the implementation into their respective .cpp files. However, how would I then be able to dynamically choose between A::PrintAlphabetPosition() and B::PrintAlphabetPosition() at runtime?
EDIT: I should mention for clarity that classes A and B act as utility classes that implement Letter differently, and they have many more functions. Furthermore, there are much more derived classes of Letter that I wish to use (not just A and B).