Created
February 7, 2011 03:13
-
-
Save joshz/813952 to your computer and use it in GitHub Desktop.
struct inheritance, polymorphism in c++
This file contains hidden or 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> | |
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; | |
} |
This file contains hidden or 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
print("test") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
run at http://codepad.org/liNMG3KD