Created
October 30, 2019 20:56
-
-
Save DarkStar1997/5d44f04b16a39cd5a146c3173fbb90bd to your computer and use it in GitHub Desktop.
A vector which should be capable of holding elements of any type implemented with polymorphism
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <memory> | |
#include <algorithm> | |
void* operator new(std::size_t size) | |
{ | |
std::cout << "Allocating " << size << " bytes\n"; | |
return malloc(size); | |
} | |
void operator delete(void* memory) | |
{ | |
std::cout << "Deallocating memory\n"; | |
free(memory); | |
} | |
struct MyData | |
{ | |
MyData() | |
{ | |
message(); | |
} | |
virtual ~MyData() | |
{ | |
message(false); | |
} | |
virtual void input(std::istream& in) = 0; | |
virtual void output(std::ostream& out) | |
{ | |
out << "MyData object"; | |
} | |
virtual void message(bool flag = true) | |
{ | |
if(flag) | |
std::cout << "Creating MyData object\n"; | |
else | |
std::cout << "Destructor of MyData class called\n"; | |
} | |
}; | |
struct MyString : MyData | |
{ | |
std::string str; | |
MyString() : str("") | |
{ | |
message(); | |
} | |
MyString(const std::string& str) : str(str) | |
{ | |
message(); | |
} | |
void message(bool flag = true) | |
{ | |
if(true) | |
std::cout << "MyString object created with value " << str << '\n'; | |
else | |
std::cout << "Destroying MyString object\n"; | |
} | |
virtual void output(std::ostream& out) | |
{ | |
out << str; | |
} | |
virtual void input(std::istream& in) | |
{ | |
in >> str; | |
} | |
~MyString() | |
{ | |
message(false); | |
} | |
}; | |
struct MyInt : MyData | |
{ | |
int num; | |
MyInt() : num(0) | |
{ | |
message(); | |
} | |
MyInt(const int& num) : num(num) | |
{ | |
message(); | |
} | |
void message(bool flag = true) | |
{ | |
if(true) | |
std::cout << "MyInt object created with value " << num << '\n'; | |
else | |
std::cout << "Destroying MyInt object\n"; | |
} | |
virtual void output(std::ostream& out) | |
{ | |
out << num; | |
} | |
virtual void input(std::istream& in) | |
{ | |
in >> num; | |
} | |
~MyInt() | |
{ | |
message(false); | |
} | |
}; | |
std::istream& operator >> (std::istream& in, MyData* data) | |
{ | |
data->input(in); | |
return in; | |
} | |
std::ostream& operator << (std::ostream& out, MyData* data) | |
{ | |
data->output(out); | |
return out; | |
} | |
int main() | |
{ | |
std::vector<std::shared_ptr<MyData>> arr; | |
arr.push_back(std::make_shared<MyString>("Hello")); | |
arr.push_back(std::make_shared<MyInt>(5)); | |
arr.shrink_to_fit(); | |
for(int i = 0; i < arr.size(); i++) | |
std::cout << arr[i] << '\n'; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment