I am trying to implement a character selection method, for a text based game and i know that it will not work the way i did it, because i am returning a refernce to an object with a lifetime limited to the scope of the method call. I have also tried to implement the method without referencing the Fighter parent class and returning a child class (Samus and Ryu) based on the players character choice, but then i would get this error: invalid abstract return type 'Fighter'.
Fighter characterSelection(int player,bool checkForBot, Fighter &fig)
{
int input;
string newName;
if(checkForBot)
{
input = (rand()%2)+1;
}
else{
cout << "Please choose your Fighter player"<<player<<": \n1. Samus\n2. Ryu\n";
input = readInput<int>();
}
if(input == 1)
{
Samus sam;
if(checkForBot)
{
cout << "Bot selected Samus!";
}
else{
cout << "Player"<<player<<" selected Samus!\nDo you wish to change your fighters name?\n1.Yes\n2.No\n";
input = readInput<int>();
if(input == 1)
{
cout << "new Name: ";
newName = readInput<string>();
changeName(newName,sam);
}
}
return sam;
}
else if(input == 2)
{
Ryu ry;
if(checkForBot)
{
cout << "Bot selected Ryu!";
}
else {
cout << "Player"<<player<<" selected Ryu!\nDo you wish to change your fighters name?\n1.Yes\n2.No\n";
input = readInput<int>();
if(input == 1)
{
cout << "new Name: ";
newName = readInput<string>();
changeName(newName,ry);
}
}
return ry;
}
}
After having chosen one character and the end of the function call, the destructor of the object is called upon, thus making the reference linked to a non-existing object.
int main()
{
int input;
string newName;
bool checkForBot;
int player=1;
while(true)
{
cout << "1. PVP \n2. PVE\n";
input = readInput<int>();
if(input == 1)
{
checkForBot = false;
//Character Selection
Fighter &fig1 = characterSelection(player,checkForBot,fig1);
player++;
Fighter &fig2 = characterSelection(player,checkForBot,fig2);
//Battle
fightPVP(fig1, fig2);
}
else if(input ==2)
{
//Character Selection
Fighter &fig1 = characterSelection(player,checkForBot,fig1);
checkForBot = true;
Fighter &bot = characterSelection(player,checkForBot,bot);
//Battle
fightPVE(fig1, bot);
}
}
return 0;
}
Is there any other way i could solve this problem, instead of referencing the parent class and then creating the child in the function call?
In this:
Fighter &fig1 = characterSelection(player,checkForBot,fig1);
you are making a reference to a local object copy returned by the function.
Returning a parent object has also the issue of object slicing; you should have that in account.
If that's not a problem, however, you can add a copy constructor to the class and just remove the reference when declaring the receiving variable:
Fighter fig1 = characterSelection(player,checkForBot,fig1);
If your object is not suited to copy, other way is to new the object in characterSelection and return a pointer (or better, shared pointer) of the base class.
In the case of your code, the compiler is right. From the function 'characterSelection' you return an instance of the abstract class Fighter which is wrong as abstract classes cannot be instantiated. You can only return a pointer or a reference (Fighter* or Figther&) to an abstract class (the pointer is generally the preferred way). From my knowledge the single way to achieve what you want using inheritance form an abstract class and a choice of a kind of Fighter at runtime is that:
#include <iostream>
class Fighter
{
public:
virtual void f() = 0;
virtual ~Fighter() {};
};
class Samus : public Fighter
{
public:
void f() { std:: cout << "Samus\n"; }
};
class Ryu : public Fighter
{
public:
void f() { std:: cout << "Ryu\n"; }
};
Fighter* getFigther()
{
int fighterCode;
std::cin >> fighterCode;
switch (fighterCode)
{
case 0: return new Samus();
case 1: return new Ryu();
default: return nullptr;
}
}
int main()
{
Fighter* myF = getFigther();
// Do what you want with the fighter
myF->f();
// Release the resources
delete myF;
}
If you want to avoid heap allocation from whatever reason, you can do that by using placement new syntax:
#include <iostream>
class Fighter
{
public:
virtual void f() = 0;
virtual ~Fighter() {};
};
class Samus : public Fighter
{
public:
void f() { std:: cout << "Samus\n"; }
};
class Ryu : public Fighter
{
public:
void f() { std:: cout << "Ryu\n"; }
};
constexpr std::size_t size()
{
constexpr std::size_t samusS = sizeof(Samus);
constexpr std::size_t ryuS = sizeof(Ryu);
return samusS < ryuS ? ryuS : samusS;
}
void getFigther(Fighter*& f)
{
int fighterCode;
std::cin >> fighterCode;
// If figtherCode is invaild you can print a message or throw an exception
switch (fighterCode)
{
case 0: new (f) Samus(); break;
case 1: new (f) Ryu(); break;
}
}
int main()
{
char space[size()];
Fighter* myF = (Fighter*) (space);
getFigther(myF);
// Do what you want with the fighter
// No delete requied
myF->f();
}
However, if you have multiple fighter classes with different sizes you will need a compile-time function to give you the maximum size of any class (representing a fighter). I don't think that approach worth the effort in your case.
Related
Yet another question about my project for my university! We are creating a cash register program which has an inventory, both held in their own respective header files with their own classes and objects.
Here is our current iteration of our header files, thought it may be messy from debugging.
Inventory.h:
class inventory
{
protected:
vector <item> itemList;
fstream infile;
public:
void printList();
void fillInventory();
void fileOpen();
};
class item
{
protected:
double price;
string name;
int amount;
friend class inventory;
};
Register.h:
class cashRegister : protected inventory
{
private:
vector <int> userChoice;
double total = 0;
public:
void input();
void printReceipt();
void calcTotal();
const double getTotal();
};
void cashRegister::input()
{
int temp;
try
{
do
{
cout << "\nPlease select an item using the corresponding item number.\n=> ";
cin >> temp;
if (cin.fail())
{
throw(256);
}
else
{
if (temp == -1)
{
break;
}
else if (temp >= 0 && temp <= 10)
{
if (inventory.stockChecker(temp) == 1)
{
userChoice.push_back(temp);
}
}
else
{
throw(1);
}
}
cout << "\n\n";
printInventory();
} while (true);
}
catch (int error)
{
cout << "Input error: " << error << endl;
cout << "Please enter a value from 0 to 10 to select an item (-1 to exit).\n";
cout << "----------------------------------------------------------------\n";
cin.clear();
cin.ignore(256, '\n');
input();
}
}
The problem here is once we pass ourselves into Register.h, we take user input then call the printInventory inventory method after every entry. But when we go to printInventory we no longer have the itemList data that the inventory object held.
Here is main.cpp for clarification on the objects:
#include"Inventory.h"
#include"Register.h"
int main()
{
inventory inv;
inv.fileOpen();
inv.fillInventory();
inv.printInventory();
cashRegister register1;
register1.input();
register1.calcTotal();
register1.printReceipt();
}
Our object inv holds a vector of item objects, which has the data members price amount name. So when we create the register1 object then try to print the inventory again, we now have an empty vector. How would I achieve being able to print the inv object's itemList or other data in general?
EDIT: Also to note I did try passing the inv object by reference and then calling the methods with that object. It did work but it felt awfully messy.
If you want to access the data of inv from a cashRegister object; instead of passing the inv object as reference every time you use it's data, you may want to hold a pointer in cashRegister class. inventory class will have member functions for manupilating and accessing it's data. Therefore you will be able to access to same cashRegister from multiple inventory objects, easily doing operations on cashRegister. With this approach, you will just need to initialize your cashRegister class with a pointer to inventory class.
class inventory
{
public:
void printList();
void changeData();
...
};
class cashRegister
{
private:
inventory* inv;
public:
cashRegister(inventory *inv)
:
inv(inv)
{}
void printInventory()
{
inv->printList();
}
...
};
int main()
{
inventory inv;
inv.fileOpen();
inv.fillInventory();
inv.printInventory();
cashRegister register1(&inv);
cashRegister register2(&inv);
register1.input();
register1.calcTotal();
register1.printReceipt();
register1.printInventory();
register2.printInventory();
}
I'm doing an assignment with virtual classes, I need to implement a pure virtual method which later will be implemented in an inherited class.
I solved a problem before with pure virtual methods which worked flawlessly, solving by myself the error i receive now ( error C2259: 'Playlist': cannot instantiate abstract class) - by implementing a method in an inherited class.
class Record
{
char* artist;
char* titlu;
int durata;
public:
Record()
{
artist = new char[50];
titlu = new char[50];
durata = 0;
}
void setArtist(char *s)
{
strcpy(artist, s);
}
char* getArtist()
{
return artist;
}
void setTitlu(char* s)
{
strcpy(titlu, s);
}
char* getTitlu()
{
return titlu;
}
void setDurata(int n)
{
int durata = n;
}
int getDurata()
{
return durata;
}
};
class Playlist
{
Record* p; /// "Record" is another class
public:
Playlist(int n)
{
p = new Record[n];
}
virtual void sortare(int n) = 0;
};
class PlaylistImplementation :public Playlist
{
public:
void sortare(int n)
{
if (n == 1)
{
cout << "1";
}
else if (n == 2)
{
cout << "2";
}
else
cout << "3";
}
};
Here is the main():
int main()
{
int n;
cout << "Number of tracks ?";
cin >> n;
Playlist x(n); /// I use VS 2019 and "x" has a red tilde underneath,
/// also error is at this line.
cin.ignore();
cin.get();
return 0;
}
I expect to instantiate an object from class Playlist.
You can't instantiate Playlist directly because it is abstract, so in main, instead of:
Playlist x(n);
you need
PlaylistImplementation x(n);
And you need a constructor in PlaylistImplementation like so:
PlaylistImplementation (int n) : PlayList (n) { }
Member 'p' of type Record in class Playlist is implicitly declared private. For access you need to add public member functions (e.g. to store data to a record).
So made a class called ‘Item’, and the object of that class will have a 100% condition at the start, the Player stores items (with name “apple” in this case) whenever I tell him to. In the degradeT function I want to pass the whole vector containing the items that the player has picked up by far and then change the condition of each Item in that vector by -1 through the chCond function.
first error:
initial value of reference to non-const must be an lvalue
second error:
'void degradeT(std::vector<Item,std::allocator<_Ty>> &)': cannot convert argument 1 from 'std::vector<Item,std::allocator<_Ty>>' to 'std::vector<Item,std::allocator<_Ty>> &'
#include "pch.h"
#include <iostream>
#include <string>
#include <vector>
using std::cout; using std::cin; using std::endl;
using std::string; using std::vector; using std::to_string;
class Item {
private:
string name; // Item name
float condition; // Item condition
bool consumable; // Is the item consumable
public:
Item() {}
Item(string a, float b, bool c) { name = a; condition = b; consumable = c; }
Item(string a, bool c) { name = a; condition = 100.f; consumable = c; }
string getName() {
return name;
}
float getCond() {
return condition;
}
bool isCons() {
return consumable;
}
void chCond(float a) { // Change Item condition
condition += a;
}
};
//-----------------------
class Player {
private:
vector<Item> plItems; // Item container
public:
Player() {}
void pickUpItem(Item a) { // Adding Items to inventory
plItems.push_back(a);
cout << a.getName() << " added to inventory!\n";
}
void checkItemConds() { // Checking condition of all items
for (unsigned int a = 0, siz = plItems.size(); a < siz; a++) {
cout << plItems[a].getName() << "'s condition is: " << plItems[a].getCond() << "%\n";
}
}
Item returnItem(unsigned int a) { // Return a specific Item
return plItems[a];
}
int getCurInvOcc() { // Get cuurent inventory occupation
return plItems.size();
}
vector<Item> getPlItems() { // Return the vector (Item container)
return plItems;
}
};
//-------------------------
void degradeT(vector<Item>& Itemss); // Degrade item after some time
//-------------------------
int main()
{
Player me; // me
string inp; // input
int num = 1; // apple 1, apple 2, apple 3...
while (inp != "exit") {
cin >> inp;
if (inp == "addApple") {
Item apple(("apple " + to_string(num)), true);
me.pickUpItem(apple);
num++;
}
if (inp == "checkItemConds") {
me.checkItemConds();
}
if (inp == "timeTick") {
// This doesn't have anything to do with time I just want to test the function manually
degradeT(me.getPlItems());
}
}
system("PAUSE");
return 0;
}
void degradeT(vector<Item> &Itemss) {
for (unsigned int a = 0, siz = Itemss.size(); a < siz; a++) {
Itemss[a].chCond(-1);
cout << Itemss[a].getName() << endl;
}
}
I'm not sure what your question is, but your error is related to the function void degradeT(vector<Item> & Itemss).
This functions expects a reference but you are passing an r-value. You can either return a reference with getPlItems() or pass an l-value to degradeT.
Recently, I started working with classes and, today, class inheritance. I created a simple program to expand my perception of inheritance. The program calculates the average grade of a class. I understand the vast majority of the code I have written, but there are some exceptions (listed below the code). Any and all help would be appreciated.
Code
#include "stdafx.h"
#include <iostream>
using namespace std;
class CAverage {
private:
double VSubCount, VAverage, VMark, VSum, VNum;
public: CAverage(int); // Constructor.
void MTake_action() {
MAsk_input(); // Calls the method “MAsk_input()“ within this class.
MCalculate_average(); // Calls the method “MCalculate_average()“ within
// this class.
MPrint_result(); // Calls the method “MPrint_result()“ within this class.
}
void MCalculate_average() {
VAverage = VSum / VNum;
}
void MAsk_input() {
VSum = 0;
VNum = 0;
int VNumber;
for (int i = 0; i < VSubCount; i++) {
cout << "Enter your " << i + 1 << " mark: ";
cin >> VNumber;
if (VNumber > 0) {
VMark = VNumber;
VSum += VMark;
VNum++;
}
}
}
void MPrint_result()
{
system("cls");
if (((VSum / 3) <= 0) || ((VSum / 3) > 10)) {
cout << "Incorrect input." << endl;
} else {
cout << "Average: " << VAverage << endl;
}
}
};
// Creates a child class and makes that this class could view/get public methods,
// variables, etc of “CAverage“.
class CGroup : public CAverage {
private:
int VClassMembers;
void MAsk_input() {
for (int i = 0; i < VClassMembers; i++) {
system("cls");
cout << "[" << i + 1 << " student]" << endl;
CAverage::MAsk_input(); // Calls the method “MAsk_input()“ within
// the parent class (“CAverage“).
}
}
public: CGroup(int, int);
void MTake_action() {
MAsk_input(); // Calls the method “MAsk_input()“ within this class.
CAverage::MCalculate_average(); // Calls the method “MCalculate_average()“
// within the parent class (“CAverage“).
CAverage::MPrint_result(); // Calls the method “MPrint_result()“ within the
// parent class (“CAverage“).
}
};
CAverage::CAverage(int VSubjectCount) {
VSubCount = VSubjectCount;
}
CGroup::CGroup(int VOther, int VInteger) : CAverage(VOther) {
VClassMembers = VInteger;
}
int main() {
CGroup avg(2, 5); // Creates an object, named “avg“.
avg.MTake_action(); // Calls the child classes' method “MTake_action()“.
return 0;
}
So, how would one explain these parts?
CAverage::CAverage(int VSubjectCount) {
VSubCount = VSubjectCount;
}
CGroup::CGroup(int VOther, int VInteger) : CAverage(VOther) {
VClassMembers = VInteger;
}
I think that this
CAverage(int);
and this
CGroup(int, int);
call the constructors? Or, are they themselves the constructors?
And, are all of the comments, made by me, correct?
I think that this
CAverage(int);
and this
CGroup(int, int);
call the constructors? Or, are they themselves the constructors?
Your second presumption is correct, both are constructors.
CAverage::CAverage(int VSubjectCount) {
VSubCount = VSubjectCount;
}
This snippet initializes the variable VSubCount within the superclass.
CGroup::CGroup(int VOther, int VInteger) : CAverage(VOther) {
VClassMembers = VInteger;
}
This is a little more complex, and shows key concepts of inheritance.
: CAverage(VOther)
Is calling the parent constructor, to initialize the private member VSubCount, in CAverage, since CGroup cannot access it.
VClassMembers = VInteger;
initializes the member VClassMembers in the subclass. Otherwise, your comments are correct.
The main question is how do I implement startTest() so that it calls runTest in all the subclasses. Thanks!
/*******************
COMPILER TEST
*******************/
class archeTest
{
protected:
short verbosity_;
public:
void setVerbosity(short v)
{
if( ((v == 1) || (v == 0) )
{
verbosity_ = v;
}
else
{
cout << " Verbosity Level Invalid " << endl;
}
}
virtual void runTest() = 0;
{
}
void startTest()
{
}
};
class testNatives : public archeTest
{
public:
void runTest()
{
testInts<short>();
testInts<int>();
testInts<long>();
testInts<unsigned short>();
testInts<unsigned int>();
testInts<unsigned long>();
}
void reportResults() const
{
}
protected:
template<class T> void testFloats()
template<class T> void testInts()
{
verbosity_ = 1;
T failMax;
short passState;
short bitDepth;
const char* a = typeid(T).name();
bool signedType = ((*a == 't') || (*a == 'j') || (*a == 'm'));
/* Bit Depth - Algorithm */
T pow2 = 1, minValue = 0, maxValue = 0, bitCount = 0, failValue = 0;
while(pow2 > 0)
{
pow2 *= 2;
maxValue = pow2-1;
bitCount++;
}
failValue = pow2;
int native1 = bitCount;
int native2 = sizeof(T)*8;
int native3 = numeric_limits<T>::digits;
if( !signedType )
{
native1++;
native3++;
}
if(verbosity_)
{
cout << endl << "**********\n" << reportType(a) << "\n**********" << endl << endl;
cout << "Bit Depth - Algorithm:\t" << native1 << endl;
cout << "Bit Depth - Sizeof:\t" << native2 << endl;
cout << "Bit Depth - File:\t" << native3 << endl;
}
if (native1 == native2 && native1 == native3)
{
cout << "Correlation:\t\tPass" << endl ;
}
else
{
cout << "Correlation:\t\tFail" << endl ;
}
cout << "Max Value:\t\t" << maxValue << endl;
cout << "Max+1 Value:\t\t" << failValue << endl;
}
string reportType(const char* c1)
{
string s1;
switch(*c1)
{
case 't':
s1 = "Unsigned short";
break;
case 'j':
s1 = "Unsigned int";
break;
case 'm':
s1 = "Unsigned long";
break;
case 's':
s1 = "Short";
break;
case 'i':
s1 = "Int";
break;
case 'l':
s1 = "Long";
break;
default:
s1 = "Switch failed";
}
return s1;
}
};
int main()
{
testNatives A;
A.runTest();
}
It is possible but to do it you will have to use an abstract factory pattern. Please read this for an overview on what the abstract pattern is and how it can do what you need.
If you can use boost in your project then you can implement your own abstract factory by using the boost::factory template.
There are a lot of other implementations for the abstract factory that you might be able to use if you do not want to roll out your own. Here is a link to one such implementation.
EDIT: In this case you will also need some mechanism to register new test cases with the factory at compile time. This can be achieved by leveraging either c++ preprocessor or templates. Here is an approach for this that uses templates.
Well, first - single responsibility principle. That in mind, your archeTest shouldn't manage alle test objects. Just have an (in)famous Manager do that!
#include <vector>
class TestManager{
std::vector<archeTest*> _tests;
public:
// either
void AddTest(archeTest* test){
_tests.push_back(test);
}
// OR
archeTest* CreateTest(/*here_be_params*/){
archeTest* test = new archeTest(/*params*/);
// do whatever
_tests.push_back(test);
return test;
}
void RunAllTests() const{
for(int i=0; i < _tests.size(); ++i)
_tests[i]->runTests();
}
// if you create tests in here, you also need to release them at the end
// ONLY do this if your created the tests with CreateTest
// or if you transfer the ownership of the test pointer to TestManager
~TestManager(){
for(int i=0; i < _tests.size(); ++i)
delete _tests[i];
}
};
Run with
TestManager tmgr;
// create all your tests, either with
// archeTest* p = tmgr.CreateTest();
// OR
// archeTest* p = new archeTest();
// tmg.AddTest(p);
// and then run with
tmgr.RunAllTests();
Again, see the comments in the TestManager implementation.
Now, if you really really don't want an extra class ... that is actually easier, but it's kinda code smell. Just add your class in the constructor of archeTest into a static linked list - problem solved! Remove it on destruction again of course. This works because every derived class xxxstructor automatically calls the base class version - the *con*structor before its own and the *de*structor after its own:
#include <list>
class archeTest{
private:
typedef std::list<archeTest*> TestList;
static TestList _all_tests;
// to erase the right test on destruction
TestList::iterator _this_test;
public:
archeTest(){
_all_tests.push_back(this);
}
~archeTest(){
_all_tests.erase(_this_test);
}
static void RunAllTests(){
for(TestList::iterator it = _all_tests.begin(); it != _all_tests.end(); ++it)
(*it)->runTests();
}
};
// in some TestManager.cpp
#include "TestManager.h"
TestManager::TestList TestManager::_all_tests;
Run it with a simple
// create all your tests;
// ...
archeTest::RunAllTests();
since it's a static member function, it doesn't need an instance.;
Note that I used a linked list, as that allows me to safely remove a test in the middle of the list without invalidating the references stored in the other test objects.
Since a lot of people were finding it difficult to follow through all the posts I listed. I implemented a version of this using boost.
The trick is the fact that when the definition for TestTemplate is expanded with the derived class definitions(new Test cases) it forces a call to the TestManager::Register method due to the initialization of the static const.
template<typename TestCase>
const unsigned Test<TestCase>::m_uTestID = TestManager::Register(boost::factory<TestCase*>());
This ensures that a functor to the constructor of the derived class is stored in the TestManager's map. Now in the TestManager I simply iterate over the map and use the functor to instantiate each Testcase and call the run method on the newly created instance.
Any class that is derived from the TestTemplate will be registered automatically, No need to manually list all of them.
#include <map>
#include <iostream>
#include <boost/function.hpp>
#include <boost/functional/factory.hpp>
class ITest {
public:
virtual void run() {
runTest();
}
virtual void runTest() = 0;
};
typedef boost::function< ITest* ()> TestFactory;
class TestManager {
public:
static int Register(TestFactory theFactory) {
std::cout<<"Registering Test Case"<<std::endl;
m_NumTests++;
m_mapAllTests[m_NumTests] = theFactory;
return m_NumTests;
}
void run() {
for(unsigned uTestID = 1; uTestID <= m_NumTests; uTestID++) {
ITest* theTestCase = m_mapAllTests[uTestID]();
theTestCase->run();
delete theTestCase;
}
}
private:
static unsigned m_NumTests;
static std::map<unsigned, TestFactory> m_mapAllTests;
};
unsigned TestManager::m_NumTests = 0;
std::map<unsigned, TestFactory> TestManager::m_mapAllTests;
template<typename TestCase>
class Test : public ITest {
public:
unsigned getID() const {
return m_uTestID;
}
private:
static const unsigned m_uTestID;
};
template<typename TestCase>
const unsigned Test<TestCase>::m_uTestID = TestManager::Register(boost::factory<TestCase*>());
class Test1 : public Test<Test1> {
public:
virtual void runTest() {
std::cout<<"Test Id:"<<getID()<<std::endl;
}
};
class Test2 : public Test<Test2> {
public:
virtual void runTest() {
std::cout<<"Test Id:"<<getID()<<std::endl;
}
};
class Test3 : public Test<Test3> {
public:
virtual void runTest() {
std::cout<<"Test Id:"<<getID()<<std::endl;
}
};
class Test4 : public Test<Test4> {
public:
virtual void runTest() {
std::cout<<"Test Id:"<<getID()<<std::endl;
}
};
int main() {
TestManager theManager;
theManager.run();
}
I did test the solution on VS05 and VS10. Below is the expected output.
Registering Test Case
Registering Test Case
Registering Test Case
Registering Test Case
Test Id:1
Test Id:2
Test Id:3
Test Id:4
Hope it clears up some confusion.
First off, you would declare startTest like this in archeTest.
virtual void startTest() = 0;
That makes it a pure virtual function that must be implemented in child classes. To call this method on a child class, you must have an object of that particular class instantiated. Then you can call startTest either through a base class pointer or through a pointer to the child class. Note that in either case the pointer must be pointing to an instantiation (concrete object) of the child class.
You might want to check out UnitTest++ (you can browse the source code here). Pay particular attention to TestMacros.h and CheckMacros.h, which, as their names imply, implement macros to automatically collect and run tests.
The following code, for example, is "a minimal C++ program to run a failing test through UnitTest++."
// test.cpp
#include <UnitTest++.h>
TEST(FailSpectacularly)
{
CHECK(false);
}
int main()
{
return UnitTest::RunAllTests();
}
You can read more at the (brief) UnitTest++ overview. I haven't delved into the details of how the TEST and CHECK macros are implemented, but they do allow you to declare tests in many different CPP files and then run them all via a single call to UnitTest::RunAllTests(). Perhaps this is close enough to what you want to do?
EDIT: never mind, my first answer didn't make any sense. In C++, you cannot obtain the list of all subclasses of a class to instantiate them, so I don't think you can implement runTests() the way you want it.