Skip to content

Instantly share code, notes, and snippets.

@kumailxp
Created July 18, 2018 09:31
Show Gist options
  • Save kumailxp/a25c035354d862a885330782f7249957 to your computer and use it in GitHub Desktop.
Save kumailxp/a25c035354d862a885330782f7249957 to your computer and use it in GitHub Desktop.
Example of using shared_ptr with inheritance
#include<iostream>
#include<memory>
#include<vector>
using namespace std;
class A {
private:
int val;
public:
A(int _v) : val(_v) {}
int getValue() const { return val; }
virtual void print() = 0;
};
class B : public A {
public:
B(int a) : A(a) {}
virtual void print() override {
cout << "This is inherited class B" << endl;
}
};
class C : public A {
public:
C(int a) : A(a) {}
virtual void print() override {
cout << "This is inherited class C" << endl;
}
};
class D : public A {
public:
D(int a) : A(a) {}
virtual void print() override {
cout << "This is inherited class D" << endl;
}
};
static void printAll(vector<A*> vecA) {
for(auto& I : vecA)
I->print();
}
static void printAll(vector<shared_ptr<A>> vecA) {
for(auto& I : vecA)
I->print();
}
int main () {
B* b0 = new B(10);
cout << "The value is: " << b0->getValue() << endl;
b0->print();
cout << "=====================================" << endl;
B* b1 = new B(100);
C* c1 = new C(101);
D* d1 = new D(102);
vector<A*> a {b1,c1,d1};
printAll(a);
cout << "=====================================" << endl;
auto b3 = make_shared<B>(200);
auto c3 = make_shared<C>(200);
auto d3 = make_shared<D>(200);
vector<shared_ptr<A>> b {c3,b3,d3};
printAll(b);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment