I have a weird problem. I made an example explaining what is the problem. I have 4 classes, one that gets a pointer to a class which is inherent to 2 others. Here is what it looks like : The inherences classes:
class classA{
public:
classA(){}
virtual std::string getType(){return "classA";}
classA& operator=(const classA& classa) {return *this;}
};
class classB: public classA {
int b;
public:
classB(int n){b=n;}
virtual std::string getType() { return "classB"; }
void setB(const int b){this->b=b;}
int getB() const{return this->b;}
};
class classC: public classA {
int c;
public:
classC(int n){c=n;}
virtual std::string getType() { return "classC"; }
void setC(const int c){this->c=c;}
int getC() const{return this->c;}
};
The only important thing is the getType()
function.
Here is now the class that get a pointer to classA
class superClass{
classA* _classA;
int nb;
public:
superClass(){nb=0;}
void addElement(classA& e){
classA *newTab=new classA[++nb]; // create tab as the same size than the other +1
for(int i=0;i<nb-1;i++)
newTab[i]=_classA[i]; // add element from the old class to the new one
newTab[nb-1]=e; // add the element
//delete[] _classA;
_classA=newTab; // now copy it to the class
//delete[] newTab;
}
classA* getClass() {return _classA;}
int getNb() const{return this->nb;}
void displayElements(){
for(int i=0;i<getNb();i++)
std::cout << _classA[i].getType() << std::endl;
}
};
addElemment() is a function that malloc a classA element with one space more, it is filled with the ancien elements then it adds the new element and here it goes. Is works BUT the problem is here. I don't use classA element, only its children. I want to add classB elements and classC elements the the superClass and get the class type with getType(); Here is the main file
int main(int argc, char const *argv[])
{
classB *classb = new classB(9);
classC *classc = new classC(10);
superClass super;
super.addElement(*classb);
super.displayElements();
// Display "classA" instead of "classB"
super.addElement(*classc);
super.displayElements();
// Display "classA" and "classA" instead "classB" and "classC"
//std::cout << classb->getType() << std::endl; // return ClassA
//std::cout << classc->getType() << std::endl; // return ClassA
return 0;
}
I just want my program displaying the right class, the child one class. The problem comes with addElement() I think. I tried to use virtual std::string getType()=0;
but it still doesn't work, it changes nothing.
I also tried using template but changes nothing and does not work
My question : I want my program displaying the child class instead of classA everytime.