I am currently doing a project and learning about inheritance in c++. However I encountered a problem that I do not know how to solve.
I will give an example code because the real one is quite difficult to understand since it is in Spanish.
In musicalsymbol.h:
class MusicalSymbol {
public:
MusicalSymbol();
virtual ~MusicalSymbol();
virtual qreal getX();
private:
...
};
musicalsymbol.cpp
MusicalSymbol::MusicalSymbol() {}
MusicalSymbol::~MusicalSymbol() {}
qreal MusicalSymbol::getX() {
return -1;
}
Now I have a child class:
note.h
class Note : public MusicalSymbol{
public:
Note();
~Note();
qreal getX() override;
private:
qreal x;
note.cpp
Note::Note() {}
Note::~Note() {}
qreal Note::getX() {
return this->x;
}
Now I have another class where I have a vector of MusicalNote
std::vector < MusicalSymbol > tab_score;
I append elements to that vector that are of the class note (and other child classes) with push_back()
but later when I try to access an element of the class like so:
tab_score[i].getX();
I always get -1 as an output, when I would like to get x
from the Note class. What would be the best way of getting a correct value.
Also it is possible to create a x
value inside the parent class and modify it from the child class?
Edit: Thanks for the information about slicing, now I know why is not working but I still can't figure out how to solve it.
Thanks to everyone and let me know if there is something that it is not clear.