// CopyAndAssignment.cpp #include #include #include class A { public: A(const std::string& s) : _s(s) {} std::string& getString() { return _s; } private: std::string _s; }; class B : public A { public: B(); B(const B& b); B& operator=(const B& b); int& operator[](int i); B& push_back(int i); void show(); private: std::vector* pV; }; B::B() : A("default string") { pV = new std::vector(); } B::B(const B& b) : A(b) { pV = new std::vector(*(b.pV)); // This works too // pV = new std::vector(); // for(unsigned int i=0; isize(); ++i) // pV->push_back((*b.pV)[i]); }; B& B::operator =(const B& b) { if(this != &b) { (A&)*this = b; pV->clear(); *pV = *b.pV; // vector assignment // could also do this: // (A&)*this = b; // delete pV; // pV = new std::vector(*(b.pV)); // vector copy // // this works too for last statement // pV = new std::vector(); // for(unsigned int i=0; isize(); ++i) // pV->push_back((*b.pV)[i]); // } return *this; } int& B::operator[](int i) { return ((*pV)[i]); } B& B::push_back(int i) { pV->push_back(i); return *this; } void B::show() { std::cout << "\n " << getString().c_str() << " : "; for(unsigned int i=0; isize(); ++i) std::cout << (*pV)[i] << " "; std::cout << "\n\n"; } void main() { B b; b.push_back(0).push_back(1).push_back(2).push_back(3); b.getString() = "original vector "; b.show(); B c = b; c.getString() = "after copy "; c.show(); B d; d = b; d.getString() = "after assignment"; d.show(); }