GLProgramming.com

home :: about :: development guides :: irc :: forums :: search :: paste :: links :: contribute :: code dump

-> Click here to learn how to get live help <-


New Paste :: Recent Pastes:: Add Line Numbers


Derived Classes by burly
#include <iostream>
#include <string>

using namespace std;

class Base
{
public:
    Base();
    Base(string name);
    virtual ~Base();
    inline string GetName() { return name; }
    inline string GetType() { return type; }
    inline virtual string Overridden() { return "I am from Base"; }

protected:
    string type;
    string name;
};

class  Derived1 : public Base
{
public:
    Derived1();
    ~Derived1();
    inline virtual string Overridden() { return "I am from Derived 1";}
};

class  Derived2 : public Base
{
public:
    Derived2();
    ~Derived2();
    inline virtual string Overridden() { return "I am from Derived 2";}
};


Base::Base()
{
    type = "base";
    name = "base";
}

Base::~Base()
{

}

Derived1::Derived1()
{
    type = "Derived 1";
    name = "Derived 1";
}

Derived1::~Derived1()
{
}

Derived2::Derived2()
{
    type = "Derived 2";
    name = "Derived 2";
}

Derived2::~Derived2()
{

}

int main()
{
    Base* b = new Base();
    Derived1* d1 = new Derived1();
    Derived2* d2 = new Derived2();

    cout << "I am the base object: " << b->GetType() << ":" << b->GetName() << endl;
    cout << "I am the derived1 object: " << d1->GetType() << ":" << d1->GetName() << endl;
    cout << "I am the derived2 object: " << d2->GetType() << ":" << d2->GetName() << endl;

    Base* b2 = d1;
    Derived1* d12 = (Derived1*)d2;
    cout << "I am the derived2 object in a derived1 pointer: " << d12->Overridden() << endl;

    return 0;
}