I would like to push an instance of Child (Parent is the base class of Child), in a vector using push_back(). But then the value of the Parent members lost. In the following example, I would like to see 70 when writing the vector to the console, but I get random value instead. What is causing this?
main.cpp:
void demo(vector<Child> &ch) {
Child c(4);
c.setPrice(70);
cout << c.getPrice() << endl; // 70
ch.push_back(c);
cout << ch[ch.size()-1].getPrice() << endl; // random value
}
int main()
{
vector<Child> ch;
demo(ch);
return 0;
}
Child.h:
#ifndef CHILD_H_INCLUDED
#define CHILD_H_INCLUDED
#include "Parent.h"
class Child : public Parent
{
private:
int siz;
public:
Child();
~Child();
Child(int);
Child(const Child&);
int getSiz() const;
void setSiz(int);
};
#endif // CHILD_H_INCLUDED
Child.cpp:
#include "Child.h"
Child::Child()
{
}
Child::Child(int siz)
{
this->siz = siz;
}
Child::Child(const Child& other)
{
siz = other.siz;
}
Child::~Child () {
}
int Child::getSiz() const
{
return siz;
}
void Child::setSiz(int s)
{
siz = s;
}
Parent.h:
#ifndef PARENT_H_INCLUDED
#define PARENT_H_INCLUDED
class Parent
{
private:
int price;
public:
Parent();
~Parent();
Parent(int);
Parent(const Parent&);
int getPrice() const;
void setPrice(int);
};
#endif // PARENT_H_INCLUDED
Parent.cpp:
#include "Parent.h"
Parent::Parent()
{
}
Parent::Parent(int price)
{
this->price = price;
}
Parent::Parent(const Parent& other)
{
price = other.price;
}
Parent::~Parent () {
}
int Parent::getPrice() const
{
return price;
}
void Parent::setPrice(int p)
{
price = p;
}
Thank you very much in advance for your help!
CodePudding user response:
The child's copy constructor only copies the child parts. It should also invoke the parent's copy constructor to let it copy the parent members.
Child::Child(const Child& other) : Parent(other)
{
siz = other.siz;
}