The Question
What is the correct way to have a member function return type be a superclass of the actual object you wan to return ?.
The Problem
Clang tidy warns me that returning subClassA
or subClassB
discards my override for myMethod
. I also, get no output - presumably because I've accidently discarded the overrided myMethod
.
The Code
#include <iostream>
using namespace std;
class SuperClass {
public :
SuperClass() {
cout << "I'm the superclass" << endl;
};
virtual std::string myMethod();
};
class SubClassA : public SuperClass {
public:
SubClassA() : SuperClass() {
cout << "I'm subclass A" << endl;
}
std::string myMethod() override {
return "A";
}
};
class SubClassB : public SuperClass {
public:
SubClassB() : SuperClass() {
cout << "I'm subclass B" << endl;
}
std::string myMethod() override {
return "B";
}
};
class Client {
private:
std::string which;
SuperClass letterFactory(){
if (which == "A") {
SubClassA subClassA;
return subClassA;
} else if (which == "B") {
SubClassB subClassB;
return subClassB;
} else {
throw std::invalid_argument("Bad");
}
}
public:
explicit Client(std::string &which) : which(which) {
letterFactory();
};
};
int main() {
Client client();
return 0;
};