Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Assignment Operator Example
// Example with a Base Class with a default assignment operator // and a Dervied Class with a crazy user-defined assignment operator. // Also, why is "myStuff" declared as "protected"? #include <iostream> using namespace std; template<class ItemType> class BaseClass { protected: ItemType myStuff; public: void setMyStuff(const ItemType &value) { myStuff = value; }; void printMyStuff() const { cout << "myStuff = " << myStuff << endl; }; }; template<class ItemType> class DerivedClass : public BaseClass<ItemType> { public: DerivedClass<ItemType>& operator=(const DerivedClass<ItemType>& rhs) { this->myStuff = rhs.myStuff + 1; return *this; }; }; int main() { cout << "Instance two BaseClass members, and call the " << endl; cout << "default (compiler-generated) assignment operator." << endl; BaseClass<int> myBaseClass1; BaseClass<int> myBaseClass2; myBaseClass1.setMyStuff(10); myBaseClass1.printMyStuff(); myBaseClass2.setMyStuff(5); myBaseClass2.printMyStuff(); myBaseClass2 = myBaseClass1; // uses the compiler-generated assignment myBaseClass2.printMyStuff(); cout << endl; cout << "Instance two DerivedClass members, and call our " << endl; cout << "crazy assignment operator." << endl; DerivedClass<int> myDerivedClass1; DerivedClass<int> myDerivedClass2; myDerivedClass1.setMyStuff(20); myDerivedClass1.printMyStuff(); myDerivedClass2.setMyStuff(3); myDerivedClass2.printMyStuff(); myDerivedClass2 = myDerivedClass1; // uses our "wrong" assignment operator myDerivedClass2.printMyStuff(); /* What do you think will happen with the following code? myBaseClass1 = myDerivedClass1; myBaseClass1.printMyStuff(); myDerivedClass2 = myBaseClass2; myDerivedClass2.printMyStuff(); */ /* What happens witht the following code? DerivedClass<string> myDerivedClass3; myDerivedClass3.setMyStuff("Hello"); myDerivedClass3.printMyStuff(); DerivedClass<string> myDerivedClass4; myDerivedClass4.setMyStuff("Hola"); myDerivedClass4.printMyStuff(); myDerivedClass4 = myDerivedClass3; */ return 0; }
run
|
edit
|
history
|
help
0
Dynamically allocated array in unique_ptr with custom deleter.
K combinator - Lazy evaluation
Uno
std::99 bottles of beer!
Combination
Mi primer ejemplo con RexTester colgado en My wall
Random values and probability distribution
template specialization inheritance solution
Dash-D compiler flag example
std::reference_wrapper