Archived

This topic is now archived and is closed to further replies.

Object oriented programming with CObject.

This topic is 5436 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I''ve always been mostly a procedural programmer rather than an OOP in its strictest sense. I use objects, but I dont frequently practice polymorphism and inheritance. I want to make use of it and take advantage of them for my current project. But I am a bit rusty. Can someone post a really basic/simple sample of a base class and a derived class that demonstrated polymorphism/virtual functions? Also a brief description of how "has a", "is a", and everything else like that can be implemented is a bonus. thanks.

Share this post


Link to post
Share on other sites

    

class Base
{
public:
virtual void DoSomething()
{
printf("Base function called.");
}
};

class Derived: public Base
{
public:
virtual void DoSomething()
{
printf("Derived function called.");
}
};


void main()
{
Base *obj1 = new Base;
Base *obj2 = new Derived;

// Outputs "Base function called."

obj1->DoSomething();

// Outputs "Derived function called."

obj2->DoSomething();

delete obj1;
delete obj2;
}



As you can see, though obj2 is a pointer to Base, the virtual function mechanism knows that it points to Derived and calls the right function.


// Website // Google // GameDev // NeHe // MSDN //

[edited by - neoztar on January 28, 2003 12:08:51 PM]

Share this post


Link to post
Share on other sites