Jump to content
  • Advertisement
Sign in to follow this  
luasitdown

Pure virtual function

This topic is 4837 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

If a class has a pure virtual function ,the class can not be instaniated. So just let a function to be pure virtual ,it will work. many people let many function in a class to be pure virtual, are there some other reason??

Share this post


Link to post
Share on other sites
Advertisement
Hi, there are a few uses.

If a class has 1 virtual function, instances of the class (objects) cannot be instantiated.

Classes with at least 1 virtual function can be used for abstract base classes ABCs, i.e. a class that contains common data & operations that can be used in any classes that inherit from the abstract base class. An example of an ABC would be 1 which held all data & operations similar between circles & ellipses.

Classes which do not have a constructor & have all pure virtual functions can be used as interfaces. All classes that inherit from an interface must provide definitions for the pure virtual functions. You can swap implementations at run-time e.g. you could define an Irenderer class that would allow you to decide at runtime if you wanted to use an OpenGL renderer or a DirectX renderer using a base class (Irenderer) pointer.

Hope that helps!

Share this post


Link to post
Share on other sites
Pure virtual member functions (Foo::Bar())


class Foo {
public:
virtual void Bar() = 0;
protected:
Foo() {};
unsigned int pooslice;
};

are abstract base classes by definition. Literally, the compiler does not have enough information to instantiate a class of this type (no definition for Foo::Bar()). Not only does Foo support overloading of Foo::Bar(), it requires it. (Otherwise, the virtuality of the function will carry over, and the derived class will be an abstract class as well.) Since you can't directly create a Foo object, the class constructor is declare protected. (generally the Happy Thing)

You can't instantiate abstract base classes, nor can you pass them to or return them from functions. You can, however pass/return a pointer/reference of one.

In your derived classes, you can initialize Foo in the initializer list:


class Bar : public Foo {
public:
Bar( unsigned int idspispopd) : Foo( idspispopd ) {};
};

:stylin:

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!