Skip to content

Instantly share code, notes, and snippets.

@joshz
Created February 7, 2011 03:13
Show Gist options
  • Save joshz/813952 to your computer and use it in GitHub Desktop.
Save joshz/813952 to your computer and use it in GitHub Desktop.
struct inheritance, polymorphism in c++
#include <iostream>
using namespace std;
struct CommonBase
{
public:
CommonBase();
CommonBase(int);
virtual ~CommonBase();
int getC(){return c;}
void setC(int c){this->c = c;}
void pubPrint(){print();}
private:
int c;
protected:
virtual void print(){cout << "CommonBase: " << c << endl;}
};
struct A : virtual public CommonBase
{
private:
int a;
public:
A();
~A();
void pubPrint(){print();}
int getA(){return a;}
void setA(int a){this->a = a;}
protected:
virtual void print();
};
A::A() : a(20)
{}
void A::print()
{
cout << "A: " << a << endl;
cout << "CommonBase: " << getC() << endl;
}
A::~A()
{
cout << "Destructor: A - 2" << endl;
}
CommonBase::~CommonBase()
{
cout << "Destructor: CommonBase - 1" << endl;
}
CommonBase::CommonBase() : c(-1)
{}
CommonBase::CommonBase(int C) : c(C)
{}
int main()
{
CommonBase *cb = new CommonBase(10);
cb->pubPrint();
cout << endl;
A *a = new A();
a->pubPrint();
cout << endl;
CommonBase *acb = new A();
a->pubPrint();
cout << endl;
delete cb;
cout << endl;
delete a;
cout << endl;
delete acb;
return 0;
}
print("test")
@joshz
Copy link
Author

joshz commented Feb 7, 2011

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment