i have the following problem, i have 2 Classes FooClass and BaseClass, and multiple SubClasses of BaseClass.
I want to add these various Subclasses into the same Vector in FooClass, because i am just implementing functions from baseclass, so i can access them through the vector key.
In the following example, each subclass sets the string name of the BaseClass with setName(), and returns it with getName(). Every subclass uses also thisFunctionisforAll() defined in the BaseClass.
The code does compile fine, except if i add vClasses.push_back(thesubclass); So i need help how i can put all these subclasses of BaseClass into the same vector.
I want to iterate through the varius subClasses of BaseClass in the FooClass vector to output their names. Example is in main.cpp
I thought i can add different subclasses to a vector if i they share the baseclass and the vector is type of the baseclass.
Here is the source:
FooClass.h:
#ifndef TESTPROJECT_FOOCLASS_H
#define TESTPROJECT_FOOCLASS_H
#include <vector>
#include "BaseClass.h"
using namespace std;
class FooClass
{
private:
vector<BaseClass> vClasses;
public:
void addClassToVector(BaseClass &classToAdd);
void getNames();
};
#endif //TESTPROJECT_FOOCLASS_H
FooClass.cpp
#include "FooClass.h"
void FooClass::addClassToVector(BaseClass &thesubclass)
{
vClasses.push_back(thesubclass);
}
void FooClass::getNames()
{
for (size_t i; i < vClasses.size(); i++)
{
cout << vClasses[i].getName() << endl;
}
}
BaseClass.h
#ifndef TESTPROJECT_BASECLASS_H
#define TESTPROJECT_BASECLASS_H
#include <iostream>
using namespace std;
class BaseClass
{
protected:
string name;
public:
virtual void setName()= 0;
virtual string getName()=0;
void thisFunctionisforAll();
};
#endif //TESTPROJECT_BASECLASS_H
BaseClass.cpp
#include "BaseClass.h"
void BaseClass::thisFunctionisforAll() {
cout << "Every subclass uses me without implementing me" << endl;
}
SubClass.h
#ifndef TESTPROJECT_SUBCLASS_H
#define TESTPROJECT_SUBCLASS_H
#include "BaseClass.h"
class SubClass : public BaseClass {
virtual void setName();
virtual string getName();
};
#endif //TESTPROJECT_SUBCLASS_H
SubClass.cpp
#include "SubClass.h"
void SubClass::setName()
{
BaseClass::name = "Class1";
}
string SubClass::getName() {
return BaseClass::name;
}
SubClass2.h
#ifndef TESTPROJECT_SUBCLASS2_H
#define TESTPROJECT_SUBCLASS2_H
#include "BaseClass.h"
class SubClass2 : public BaseClass
{
virtual void setName();
virtual string getName();
};
#endif //TESTPROJECT_SUBCLASS2_H
SubClass2.cpp
#include "SubClass2.h"
void SubClass2::setName()
{
BaseClass::name = "Class 2";
}
string SubClass2::getName() {
return BaseClass::name;
}
main.cpp
#include "FooClass.h"
void FooClass::addClassToVector(BaseClass &thesubclass)
{
vClasses.push_back(thesubclass);
}
void FooClass::getNames()
{
for (size_t i; i < vClasses.size(); i++)
{
cout << vClasses[i].getName() << endl;
}
}
I think the solution will be simple, but i am experienced in PHP and there i hadn't such issues.